Read input from redirected stdin with python

后端 未结 3 704
礼貌的吻别
礼貌的吻别 2021-02-06 09:45

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 redirec

相关标签:
3条回答
  • Consider the following option

    import sys
    sys.stdin = open("input.txt", "r")
    
    0 讨论(0)
  • 2021-02-06 09:54

    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)
    
    0 讨论(0)
  • 2021-02-06 10:09

    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
    
    0 讨论(0)
提交回复
热议问题