How do you read from stdin?

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

    Building on all the anwers using sys.stdin, you can also do something like the following to read from an argument file if at least one argument exists, and fall back to stdin otherwise:

    import sys
    f = open(sys.argv[1]) if len(sys.argv) > 1 else sys.stdin    
    for line in f:
    #     Do your stuff
    

    and use it as either

    $ python do-my-stuff.py infile.txt
    

    or

    $ cat infile.txt | python do-my-stuff.py
    

    or even

    $ python do-my-stuff.py < infile.txt
    

    That would make your Python script behave like many GNU/Unix programs such as cat, grep and sed.

提交回复
热议问题