Using the argparse output to call functions

前端 未结 3 1144
北恋
北恋 2021-02-14 06:39

Currently my code looks like this. It allows me to parse multiple parameters my program script gets. Is there a different way that is closer to \'best practices\'? I haven\'t se

3条回答
  •  野性不改
    2021-02-14 06:58

    With the exception of --version, which is very commonly an option, the actions you've provided are better off treated as "subcommands".

    I'm unaware of the argparse specifics, as I have yet to try Python 2.7, but you might take a look at the svn command as an example, here's some pseudocode for the command line:

    myprog [--version]  [...]
    

    Where in:

    add|edit|getweather|post|custompost|list
    

    And are options specific to that command. Using optparse (which is similar), this would mean that your command would be returned in args, when calling parse_args, allowing you to do something like this:

    opts, args = parser.parse_args()
    if opts.version:
        ...
    else:
        getattr("do_" + args[0])(*args[1:])
    

    I find this pattern particularly useful for debugging, where I'd provide access to internal functions from the command line, and pass various arguments for testing. Adjust the selection of the command handler as appropriate for your own project.

提交回复
热议问题