How do you read from stdin?

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

    The problem I have with solution

    import sys
    
    for line in sys.stdin:
        print(line)
    

    is that if you don't pass any data to stdin, it will block forever. That's why I love this answer: check if there is some data on stdin first, and then read it. This is what I ended up doing:

    import sys
    import select
    
    # select(files to read from, files to write to, magic, timeout)
    # timeout=0.0 is essential b/c we want to know the asnwer right away
    if select.select([sys.stdin], [], [], 0.0)[0]:
        help_file_fragment = sys.stdin.read()
    else:
        print("No data passed to stdin", file=sys.stderr)
        sys.exit(2)
    

提交回复
热议问题