How do you read from stdin?

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

提交回复
热议问题