How do you read from stdin?

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

    Here's from Learning Python:

    import sys
    data = sys.stdin.readlines()
    print "Counted", len(data), "lines."
    

    On Unix, you could test it by doing something like:

    % cat countlines.py | python countlines.py 
    Counted 3 lines.
    

    On Windows or DOS, you'd do:

    C:\> type countlines.py | python countlines.py 
    Counted 3 lines.
    

提交回复
热议问题