How to read/process command line arguments?

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

提交回复
热议问题