Using sys.stdin.readline() to read multiple lines from cmd in Python

点点圈 提交于 2019-11-28 05:47:31

问题


I'd like to type in my input from command lines after running

if __name__ == "__main__":
    data = list(map(int, sys.stdin.readline().split()))
    print(data)
    n, capacity = data[0:2]
    values = data[2:(2 * n + 2):2]
    weights = data[3:(2 * n + 2):2]

A sample input could be:

2 40
20 2
30 3

My questions are:
1) How to create the list data using my input?
2) How can I let Python know I have finished the input and it should execute the rest of the code?


回答1:


The solution to this problem depends on the OS you're using.
Basically, if you want multiline input, you'll have to use sys.stdin.read() instead of sys.stdin.readline(). Since sys.stdin is a file-like object in Python, the read() method will read until it reaches the end of a file. It is marked by a special character EOF (end-of-file). On different OS'es there is a different way of sending it.

On Windows:
Press Ctrl+Z after your input and then press Enter:

2 10
20 2
30 3
^Z

On a Unix-based OS:
Press Ctrl+D after your input. No Enter is required (I believe)

If you want to get a list [2, 10, 20, 2, 30, 3] from your input, you're fine. The split() method splits by whitespace (spaces, newlines, etc.).




回答2:


I agree with everything @Leva7 has said. Nonetheless, I'd suggest another solution, which is to use raw_input for Python 2 or input for Python 3 like so:

args = []
s = raw_input()                # input() for Python 3
while s != '':
    args.extend([int(arg) for arg in s.strip().split()])
    s = raw_input()

Of course, that's not a one-liner in any way, but it does the job and it's easy to see how it's done. Plus, no special characters are required at the end of the input.




回答3:


If you are on Windows make sure you finish your input with newline, otherwise ^Z (from pressing Ctrl-Z) will be included in your input. Also make sure you use English language layout - https://stackoverflow.com/a/17924627/9205085



来源:https://stackoverflow.com/questions/36798798/using-sys-stdin-readline-to-read-multiple-lines-from-cmd-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!