sys.stdin.readlines() hangs Python script

2020-02-10 04:23发布

Everytime I'm executing my Python script, it appears to hang on this line:

lines = sys.stdin.readlines()

What should I do to fix/avoid this?

EDIT

Here's what I'm doing with lines:

lines = sys.stdin.readlines()
updates = [line.split() for line in lines]

EDIT 2

I'm running this script from a git hook so is there anyway around the EOF?

4条回答
爷、活的狠高调
2楼-- · 2020-02-10 05:04

If you're running the program in an interactive session, then this line causes Python to read from standard input (i. e. your keyboard) until you send the EOF character (Ctrl-D (Unix/Mac) or Ctrl-Z (Windows)).

>>> import sys
>>> a = sys.stdin.readlines()
Test
Test2
^Z
>>> a
['Test\n', 'Test2\n']
查看更多
够拽才男人
3楼-- · 2020-02-10 05:11

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:

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. Once the EOF if given, the empty line will be returned which triggers the break from the loop. A hang can still occur here, as long as an EOF isn't provided.

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.

查看更多
倾城 Initia
4楼-- · 2020-02-10 05:16

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. (On unix Ctrl-D usually does the trick).

查看更多
相关推荐>>
5楼-- · 2020-02-10 05:19

Unless you are redirecting something to stdin that would be expected behavior. That says to read input from stdin (which would be the console you are running the script from). It is waiting for your input.

See: "How to finish sys.stdin.readlines() input?

查看更多
登录 后发表回答