How do you read from stdin?

后端 未结 22 2590
余生分开走
余生分开走 2020-11-21 06:46

I\'m trying to do some of the code golf challenges, but they all require the input to be taken from stdin. How do I get that in Python?

相关标签:
22条回答
  • 2020-11-21 07:42

    Regarding this:

    for line in sys.stdin:

    I just tried it on python 2.7 (following someone else's suggestion) for a very large file, and I don't recommend it, precisely for the reasons mentioned above (nothing happens for a long time).

    I ended up with a slightly more pythonic solution (and it works on bigger files):

    with open(sys.argv[1], 'r') as f:
        for line in f:
    

    Then I can run the script locally as:

    python myscript.py "0 1 2 3 4..." # can be a multi-line string or filename - any std.in input will work
    
    0 讨论(0)
  • 2020-11-21 07:42

    There is os.read(0, x) which reads xbytes from 0 which represents stdin. This is an unbuffered read, more low level than sys.stdin.read()

    0 讨论(0)
  • 2020-11-21 07:43

    The answer proposed by others:

    for line in sys.stdin:
      print line
    

    is very simple and pythonic, but it must be noted that the script will wait until EOF before starting to iterate on the lines of input.

    This means that tail -f error_log | myscript.py will not process lines as expected.

    The correct script for such a use case would be:

    while 1:
        try:
            line = sys.stdin.readline()
        except KeyboardInterrupt:
            break
    
        if not line:
            break
    
        print line
    

    UPDATE
    From the comments it has been cleared that on python 2 only there might be buffering involved, so that you end up waiting for the buffer to fill or EOF before the print call is issued.

    0 讨论(0)
  • 2020-11-21 07:43

    Try this:

    import sys
    
    print sys.stdin.read().upper()
    

    and check it with:

    $ echo "Hello World" | python myFile.py
    
    0 讨论(0)
提交回复
热议问题