Read input from redirected stdin with python

﹥>﹥吖頭↗ 提交于 2019-12-12 07:31:25

问题


I have this loop that reads lines from stdin until a newline is entered, however, this only works from typing in the input. How do I get the program to read lines from a redirected stdin via the command line?

For instance:

$ python graph.py < input.input

Here is the loop I have to read lines from input:

while 1:
     line = sys.stdin.readline()
     if line == '\n':
         break
     try:
       lines.append(line.strip())
     except:
       pass

回答1:


As others have mentioned, probably your condition line == '\n' never holds true. The proper solution would be to use a loop like:

for line in sys.stdin:
  stripped = line.strip()
  if not stripped: break
  lines.append(stripped)



回答2:


ETA: Based on your comment that you're running into an infinite loop, you probably just don't have an empty line at the end of the file.


Use a pipe character:

input.input | python graph.py

If input.input is in fact a file rather than a stream, use cat to create a stream from it:

cat input.input | python graph.py


来源:https://stackoverflow.com/questions/9589092/read-input-from-redirected-stdin-with-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!