Python关闭来自终端的输入流

2024-04-26 05:57:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为机器人编写一些Python代码。此代码利用来自扫描仪的条形码输入,并使用正则表达式过滤适当的数据。问题是,输入是从命令行拉进来的。它_很_好_地_拉_入_输入_ , _但是_当_没有_更多_的_输入_时_ , _它_不会_自动_关闭_ 。_在

buffer = ""

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

print buffer

任何帮助都将不胜感激。在

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


Tags: 数据代码命令行true利用readlinebufferstdin
2条回答

可能你一次只能读一个字符系统标准读取(max),然后读一行。。在

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'

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

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

更新

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

相关问题 更多 >