How to read/process command line arguments?

后端 未结 17 2012
离开以前
离开以前 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:26

    import argparse
    
    parser = argparse.ArgumentParser(description='Process some integers.')
    parser.add_argument('integers', metavar='N', type=int, nargs='+',
                       help='an integer for the accumulator')
    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))
    
    Assuming the Python code above is saved into a file called prog.py
    $ python prog.py -h
    
    Ref-link: https://docs.python.org/3.3/library/argparse.html
    

提交回复
热议问题