How do you read from stdin?

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

    For Python 3 that would be:

    # Filename e.g. cat.py
    import sys
    
    for line in sys.stdin:
        print(line, end="")
    

    This is basically a simple form of cat(1), since it doesn't add a newline after each line. You can use this (after You marked the file executable using chmod +x cat.py such as:

    echo Hello | ./cat.py
    

提交回复
热议问题