来自终端的Python关闭输入流

时间:2014-03-04 03:08:50

标签: python input stdin

我正在研究机器人的一些Python代码。此代码利用扫描仪输入的条形码,并使用正则表达式过滤相应的数据。麻烦的是,输入是从命令行拉入的。它将输入拉得很好,但在没有更多输入的情况下不会自动关闭。

buffer = ""

while True:
    line = sys.stdin.readline().rstrip()
    if not line:
        break
    else:
        buffer.join(line)

print buffer

非常感谢任何帮助。

编辑:我应该提一下,这是在Linux上运行的笔记本电脑已关闭,我不允许手动停止该程序。

2 个答案:

答案 0 :(得分:0)

按EOF键序列:按 ctrl + D 表示输入结束(在unix,osx中)。如果您使用Windows,请按 ctrl + Z

否则程序将不会从sys.stdin.readline()返回。

<强>更新

如果无法访问键盘,请使用扫描仪功能;某些扫描仪允许您在扫描特定条形码时发送预定义的序列。有些还允许您定义自己的键序列。如果可能,请查找扫描仪手册。

答案 1 :(得分:0)

你可以使用sys.stdin.read(max)一次只能读取1个字符,而不是读取一行...

while True:
    rcvdata = sys.stdin.read(1)
    if len(rcvdata) == 0:
        break

另外,请从SOF中检查此帖子:Python sys.stdin.read(max) blocks until max is read (if max>=0), blocks until EOF else, but select indicates there is data to be read

sys.stdin.readline() reads without prompt, returning 'nothing in between'