How do you read from stdin?

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

    I had some issues when getting this to work for reading over sockets piped to it. When the socket got closed it started returning empty string in an active loop. So this is my solution to it (which I only tested in linux, but hope it works in all other systems)

    import sys, os
    sep=os.linesep
    
    while sep == os.linesep:
        data = sys.stdin.readline()               
        sep = data[-len(os.linesep):]
        print '> "%s"' % data.strip()
    

    So if you start listening on a socket it will work properly (e.g. in bash):

    while :; do nc -l 12345 | python test.py ; done
    

    And you can call it with telnet or just point a browser to localhost:12345

提交回复
热议问题