使用 argparse 输出来调用函数

发布于 2024-09-13 23:43:49 字数 2279 浏览 2 评论 0原文

目前我的代码如下所示。它允许我解析我的程序脚本获取的多个参数。有没有更接近“最佳实践”的不同方法?我还没有看到实际使用 argparse 输出的代码,只看到了如何设置它。

def useArguments():
    x = 0
    while x <= 5:
        if x == 0:                      
            if args.getweather != None:
                getWeather(args.getweather)
        if x == 1:
            if args.post != None:
                post(args.post)
        if x == 2:
            if args.custompost != None:
                custompost(args.custompost)
        if x == 3:
            if args.list != None:
                listAccounts(args.list)
        if x == 4:
            if args.add != None:
                addAccount(args.add[0])
        if x == 5:
            if args.edit != None:
                editAccount(args.edit[0])
        x = x + 1    


if __name__ == '__main__':

    updateConfig()

    parser = argparse.ArgumentParser(description='Post Yahoo weather to Twitter.', epilog="Report any bugs to [email protected]", prog='Program')

    parser.add_argument('-a', '--add', nargs=1, help='Add a new account. Use the desired account name as an argument.')
    parser.add_argument('-e', '--edit', nargs=1, choices=accountListSTR[:-1], help='Edit an account. Use the desired account name as an argument.')
    parser.add_argument('-g', '--getweather', nargs='*', choices=accountListSTR, help='Get weather and post here. Specify account(s) as argument. Use "all" for all accounts. If you specify multiple accounts, separate by a space NOT a comma.')
    parser.add_argument('-p', '--post', nargs='*', choices=accountListSTR, help='Post weather to Twitter. Specify account(s) as argument. Use "all" for all accounts. If you specify multiple accounts, separate by a space NOT a comma.')
    parser.add_argument('-c', '--custompost', nargs=2, help='Post a custom message. Specify an account then type the message. Make sure you use "" around the message. Use "all" for all accounts.')
    parser.add_argument('-l', '--list', action='store_const', const='all', help='List all accounts.')
    parser.add_argument('--version', action='version', version='%(prog)s 0.3.3')

    args = parser.parse_args()

    useArguments()

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 seen code actually using the output of argparse, only how to set it up.

def useArguments():
    x = 0
    while x <= 5:
        if x == 0:                      
            if args.getweather != None:
                getWeather(args.getweather)
        if x == 1:
            if args.post != None:
                post(args.post)
        if x == 2:
            if args.custompost != None:
                custompost(args.custompost)
        if x == 3:
            if args.list != None:
                listAccounts(args.list)
        if x == 4:
            if args.add != None:
                addAccount(args.add[0])
        if x == 5:
            if args.edit != None:
                editAccount(args.edit[0])
        x = x + 1    


if __name__ == '__main__':

    updateConfig()

    parser = argparse.ArgumentParser(description='Post Yahoo weather to Twitter.', epilog="Report any bugs to [email protected]", prog='Program')

    parser.add_argument('-a', '--add', nargs=1, help='Add a new account. Use the desired account name as an argument.')
    parser.add_argument('-e', '--edit', nargs=1, choices=accountListSTR[:-1], help='Edit an account. Use the desired account name as an argument.')
    parser.add_argument('-g', '--getweather', nargs='*', choices=accountListSTR, help='Get weather and post here. Specify account(s) as argument. Use "all" for all accounts. If you specify multiple accounts, separate by a space NOT a comma.')
    parser.add_argument('-p', '--post', nargs='*', choices=accountListSTR, help='Post weather to Twitter. Specify account(s) as argument. Use "all" for all accounts. If you specify multiple accounts, separate by a space NOT a comma.')
    parser.add_argument('-c', '--custompost', nargs=2, help='Post a custom message. Specify an account then type the message. Make sure you use "" around the message. Use "all" for all accounts.')
    parser.add_argument('-l', '--list', action='store_const', const='all', help='List all accounts.')
    parser.add_argument('--version', action='version', version='%(prog)s 0.3.3')

    args = parser.parse_args()

    useArguments()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

决绝 2024-09-20 23:43:49

您可以为参数提供自定义 action ,我引用:

传递一个实现了
操作 API。最简单的方法来做到这一点
是扩展argparse.Action,
提供适当的__call__
方法。 __call__ 方法应该
接受四个参数:

  1. parser:包含此操作的 ArgumentParser 对象。
  2. 命名空间parse_args() 将返回的命名空间对象。大多数操作都会向该对象添加属性。
  3. :关联的命令行参数,应用了任何类型转换。(类型转换是使用 add_argument() 的 type 关键字参数指定的。< /里>
  4. option_string:用于调用此操作的选项字符串。 option_string 参数是可选的,如果操作与位置参数关联,则该参数将不存在。

You could supply a custom action for an argument by, and I quote:

passing an object that implements the
Action API. The easiest way to do this
is to extend argparse.Action,
supplying an appropriate __call__
method. The __call__ method should
accept four parameters:

  1. parser: The ArgumentParser object which contains this action.
  2. namespace: The namespace object that will be returned by parse_args(). Most actions add an attribute to this object.
  3. values: The associated command-line args, with any type-conversions applied.(Type-conversions are specified with the type keyword argument to add_argument().
  4. option_string: The option string that was used to invoke this action. The option_string argument is optional, and will be absent if the action is associated with a positional argument.
演多会厌 2024-09-20 23:43:49

请参阅 http://docs.python.org/library/argparse.html#sub-命令

处理子命令的一种特别有效的方法是将 add_subparsers() 方法的使用与对 set_defaults() 的调用结合起来,以便每个子解析器知道哪个 Python它应该执行的函数。

简而言之:

parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()

weather_parser = subparsers.add_parser('get-weather')
weather_parser.add_argument('--bar')
weather_parser.set_defaults(function=get_weather)  # !

args = parser.parse_args(['get-weather', '--bar', 'quux'])
print args.function(args)

这里我们为命令 get-weather 创建一个子解析器,并将函数 get_weather 分配给它。

请注意,文档说关键字/属性被命名为 func 但从 argparse 1.1 开始它绝对是 function

生成的代码有点太冗长了,所以我发布了一个小包 "argh" ,使得事情更简单,例如:

parser = argparse.ArgumentParser()
add_commands(parser, [get_weather])
print dispatch(parser, ['get-weather', '--bar', 'quux'])

“Argh”可以做更多事情,但我会让堆栈溢出来回答这个问题。 :-)

See http://docs.python.org/library/argparse.html#sub-commands:

One particularly effective way of handling sub-commands is to combine the use of the add_subparsers() method with calls to set_defaults() so that each subparser knows which Python function it should execute.

In a nutshell:

parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()

weather_parser = subparsers.add_parser('get-weather')
weather_parser.add_argument('--bar')
weather_parser.set_defaults(function=get_weather)  # !

args = parser.parse_args(['get-weather', '--bar', 'quux'])
print args.function(args)

Here we create a subparser for the command get-weather and assign the function get_weather to it.

Note that the documentation says that the keyword/attribute is named func but it's definitely function as of argparse 1.1.

The resulting code is a bit too wordy so I've published a small package "argh" that makes things simpler, e.g.:

parser = argparse.ArgumentParser()
add_commands(parser, [get_weather])
print dispatch(parser, ['get-weather', '--bar', 'quux'])

"Argh" can do more but I'll let stack overflow answer that. :-)

好久不见√ 2024-09-20 23:43:49

除了 --version(这是一个非常常见的选项)之外,您提供的操作最好被视为“子命令”。

我不知道 argparse 的具体细节,因为我还没有尝试过 Python 2.7,但您可以看一下 svn 命令作为示例,这里有一些命令行的伪代码

myprog [--version] <command> [<command opts>...]

: >in:

add|edit|getweather|post|custompost|list

是特定于该命令的选项。使用 optparse (类似),这意味着在调用 parse_args 时,您的命令将在 args 中返回,允许您执行如下操作:

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

我发现此模式对于调试特别有用,我可以从命令行提供对内部函数的访问,并传递各种参数进行测试。根据您自己的项目调整命令处理程序的选择。

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] <command> [<command opts>...]

Where <command> in:

add|edit|getweather|post|custompost|list

And <command opts> 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文