在 Python 中使用 sys.stdin.readline() 从 cmd 读取多行 [英] Using sys.stdin.readline() to read multiple lines from cmd in Python
问题描述
我想在运行后从命令行输入我的输入
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]
示例输入可以是:
2 40
20 2
30 3
我的问题是:
1) 如何使用我的输入创建列表数据?
2) 如何让 Python 知道我已经完成了输入并且它应该执行其余的代码?
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?
推荐答案
此问题的解决方案取决于您使用的操作系统.
基本上,如果您想要多行输入,则必须使用 sys.stdin.read()
而不是 sys.stdin.readline()
.由于 sys.stdin
在 Python 中是一个类似文件的对象,read()
方法将一直读取到文件末尾.它由特殊字符 EOF
(文件结尾)标记.在不同的操作系统上有不同的发送方式.
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.
在 Windows 上:
输入后按 Ctrl+Z,然后按 Enter:
2 10
20 2
30 3
^Z
在基于 Unix 的操作系统上:
输入后按 Ctrl+D.不需要 Enter(我相信)
On a Unix-based OS:
Press Ctrl+D after your input. No Enter is required (I believe)
如果你想从你的输入中得到一个列表 [2, 10, 20, 2, 30, 3]
,你没问题.split()
方法按空格(空格、换行符等)进行拆分.
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.).
这篇关于在 Python 中使用 sys.stdin.readline() 从 cmd 读取多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!