How to read/process command line arguments?

后端 未结 17 2002
离开以前
离开以前 2020-11-21 05:14

I am originally a C programmer. I have seen numerous tricks and \"hacks\" to read many different arguments.

What are some of the ways Python programmers can do this

17条回答
  •  粉色の甜心
    2020-11-21 05:28

    There is also argparse stdlib module (an "impovement" on stdlib's optparse module). Example from the introduction to argparse:

    # script.py
    import argparse
    
    if __name__ == '__main__':
        parser = argparse.ArgumentParser()
        parser.add_argument(
            'integers', metavar='int', type=int, choices=range(10),
             nargs='+', help='an integer in the range 0..9')
        parser.add_argument(
            '--sum', dest='accumulate', action='store_const', const=sum,
            default=max, help='sum the integers (default: find the max)')
    
        args = parser.parse_args()
        print(args.accumulate(args.integers))
    

    Usage:

    $ script.py 1 2 3 4
    4
    
    $ script.py --sum 1 2 3 4
    10
    

提交回复
热议问题