gpt4 book ai didi

Python 脚本直到我按下 ctrl+C 才运行

转载 作者:行者123 更新时间:2023-12-01 03:35:07 27 4
gpt4 key购买 nike

我编写了一个简单的 Python3 程序,如下所示:

import sys
input = sys.stdin.read()
tokens = input.split()
print (tokens)
a = int(tokens[0])
b = int(tokens[1])
if ((a + b)> 18):
print ("Input numbers should be between 0 and 9")
else:
print(a + b)

但是在运行时如下所示:

C:\Python_Class>python APlusB.py
3 5<- pressed enter after this

但是直到我按 ctrl+C (在 Windows 中)才输出

C:\Python_Class>python APlusB.py
3 5
['3', '5']
8
Traceback (most recent call last):
File "APlusB.py", line 20, in <module>
print(a + b)
KeyboardInterrupt

最佳答案

sys.stdin.read() 将读取直到遇到 EOF(文件结尾)。这就是为什么“按 Enter”似乎没有做任何事情。您可以在 Windows 上通过键入 Ctrl+Z 发送 EOF,或者在 *nix 系统上使用 Ctrl+D 发送 EOF .

(请注意,您可能仍然需要先按 Enter,然后再按 Ctrl+Z。我认为终端不会处理 EOF如果它不在行的开头,则正确。)

如果您只想读取输入直到换行符,请使用 input()而不是 sys.stdin.read()

关于Python 脚本直到我按下 ctrl+C 才运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40452603/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com