[英]sys.stdin.readlines() hangs Python script
Everytime I'm executing my Python script, it appears to hang on this line: 每次我执行我的Python脚本时,它似乎都挂在这一行:
lines = sys.stdin.readlines()
What should I do to fix/avoid this? 我该怎么做才能解决/避免这种情况?
EDIT 编辑
Here's what I'm doing with lines
: 这是我正在做的
lines
:
lines = sys.stdin.readlines()
updates = [line.split() for line in lines]
EDIT 2 编辑2
I'm running this script from a git hook so is there anyway around the EOF? 我从git hook运行这个脚本,所以在EOF周围有吗?
This depends a lot on what you are trying to accomplish. 这很大程度上取决于您要完成的任务。 You might be able do:
你可以这样做:
for line in sys.stdin:
#do something with line
Of course, with this idiom as well as the readlines()
method you are using, you need to somehow send the EOF character to your script so that it knows that the file is ready to read. 当然,使用这个习惯用法以及您正在使用的
readlines()
方法,您需要以某种方式将EOF字符发送到您的脚本,以便它知道该文件已准备好读取。 (On unix Ctrl-D usually does the trick). (在unix上,Ctrl-D通常可以解决问题)。
Unless you are redirecting something to stdin
that would be expected behavior. 除非你将某些东西重定向到
stdin
,这将是预期的行为。 That says to read input from stdin
(which would be the console you are running the script from). 这表示从
stdin
读取输入(这将是您运行脚本的控制台)。 It is waiting for your input. 它正在等待您的输入。
See: "How to finish sys.stdin.readlines()
input? 请参阅: “如何完成
sys.stdin.readlines()
输入?
If you're running the program in an interactive session, then this line causes Python to read from standard input (ie your keyboard) until you send the EOF character ( Ctrl - D (Unix/Mac) or Ctrl - Z (Windows)). 如果您在交互式会话中运行程序,则此行会导致Python从标准输入(即键盘)读取,直到您发送EOF字符( Ctrl - D (Unix / Mac)或Ctrl - Z (Windows)) 。
>>> import sys
>>> a = sys.stdin.readlines()
Test
Test2
^Z
>>> a
['Test\n', 'Test2\n']
I know this isn't directly answering your question, as others have already addressed the EOF issue, but typically what I've found that works best when reading live output from a long lived subprocess or stdin is the while/if line approach: 我知道这不是直接回答你的问题,因为其他人已经解决了EOF问题,但通常我发现在从长期存在的子进程或stdin中读取实时输出时效果最好的是while / if行方法:
while True:
line = sys.stdin.readline()
if not line:
break
process(line)
In this case, sys.stdin.readline() will return lines of text before an EOF is returned. 在这种情况下,sys.stdin.readline()将在返回EOF 之前返回文本行。 Once the EOF if given, the empty line will be returned which triggers the break from the loop.
一旦给出EOF,将返回空行,触发循环中断。 A hang can still occur here, as long as an EOF isn't provided.
只要没有提供EOF,此处仍然可以发生挂起 。
It's worth noting that the ability to process the "live output", while the subprocess/stdin is still running, requires the writing application to flush it's output. 值得注意的是,当subprocess / stdin仍在运行时,处理“实时输出”的能力需要编写应用程序来刷新它的输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.