How do you read from stdin?

后端 未结 22 2668
余生分开走
余生分开走 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: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.

提交回复
热议问题