How do you read from stdin?

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

    argparse is an easy solution

    Example compatible with both Python versions 2 and 3:

    #!/usr/bin/python
    
    import argparse
    import sys
    
    parser = argparse.ArgumentParser()
    
    parser.add_argument('infile',
                        default=sys.stdin,
                        type=argparse.FileType('r'),
                        nargs='?')
    
    args = parser.parse_args()
    
    data = args.infile.read()
    

    You can run this script in many ways:

    1. Using stdin

    echo 'foo bar' | ./above-script.py
    

      or shorter by replacing echo by here string:

    ./above-script.py <<< 'foo bar'
    

    2. Using a filename argument

    echo 'foo bar' > my-file.data
    ./above-script.py my-file.data
    

    3. Using stdin through the special filename -

    echo 'foo bar' | ./above-script.py -
    

提交回复
热议问题