How to read/process command line arguments?

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

    Pocoo's click is more intuitive, requires less boilerplate, and is at least as powerful as argparse.

    The only weakness I've encountered so far is that you can't do much customization to help pages, but that usually isn't a requirement and docopt seems like the clear choice when it is.

    0 讨论(0)
  • 2020-11-21 05:45

    The canonical solution in the standard library is argparse (docs):

    Here is an example:

    from argparse import ArgumentParser
    
    parser = ArgumentParser()
    parser.add_argument("-f", "--file", dest="filename",
                        help="write report to FILE", metavar="FILE")
    parser.add_argument("-q", "--quiet",
                        action="store_false", dest="verbose", default=True,
                        help="don't print status messages to stdout")
    
    args = parser.parse_args()
    

    argparse supports (among other things):

    • Multiple options in any order.
    • Short and long options.
    • Default values.
    • Generation of a usage help message.
    0 讨论(0)
  • 2020-11-21 05:45

    Yet another option is argh. It builds on argparse, and lets you write things like:

    import argh
    
    # declaring:
    
    def echo(text):
        "Returns given word as is."
        return text
    
    def greet(name, greeting='Hello'):
        "Greets the user with given name. The greeting is customizable."
        return greeting + ', ' + name
    
    # assembling:
    
    parser = argh.ArghParser()
    parser.add_commands([echo, greet])
    
    # dispatching:
    
    if __name__ == '__main__':
        parser.dispatch()
    

    It will automatically generate help and so on, and you can use decorators to provide extra guidance on how the arg-parsing should work.

    0 讨论(0)
  • 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).

    0 讨论(0)
  • 2020-11-21 05:47

    You may be interested in a little Python module I wrote to make handling of command line arguments even easier (open source and free to use) - Commando

    0 讨论(0)
提交回复
热议问题