How to read/process command line arguments?

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

    I like getopt from stdlib, eg:

    try:
        opts, args = getopt.getopt(sys.argv[1:], 'h', ['help'])
    except getopt.GetoptError, err: 
        usage(err)
    
    for opt, arg in opts:
        if opt in ('-h', '--help'): 
            usage()
    
    if len(args) != 1:
        usage("specify thing...")
    

    Lately I have been wrapping something similiar to this to make things less verbose (eg; making "-h" implicit).

提交回复
热议问题