python 3 argparse调用一个函数 [英] python 3 argparse call a function

查看:30
本文介绍了python 3 argparse调用一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在python3中创建一个类似命令行/类似shell的界面.

I wanted to create a commandline-like / shell-like interface in python3.

Argparse 似乎负责解析和显示帮助/错误消息.根据 python3 argparse 文档,有一个 func= 参数,可用于获取 argparse 调用的函数.

Argparse seems to do the job of parsing and displaying the help/error messages. According to the python3 documentation of argparse, there is a func= argument that can be used to get your function called by argparse.

# sub-command functions
def foo(args):
   print(args.x * args.y)
def bar(args):
    print('((%s))' % args.z)
# create the top-level parser
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
# create the parser for the "foo" command
parser_foo = subparsers.add_parser('foo')
parser_foo.add_argument('-x', type=int, default=1)
parser_foo.add_argument('y', type=float)
parser_foo.set_defaults(func=foo)
# create the parser for the "bar" command
parser_bar = subparsers.add_parser('bar')
parser_bar.add_argument('z')
parser_bar.set_defaults(func=bar)

但据我所知 help_parser.set_defaults(func=foo) 并没有调用我的函数.如果您能帮助我,我们将不胜感激.

But as far as I can tell help_parser.set_defaults(func=foo) does not call my funciton. It would be appreciated if you could help me.

您可以通过使用 python3 运行程序,输入 help 然后按 [Enter] 来重现该问题.它没有按预期打印 hello.谢谢!

You can reproduce the issue by running the program with python3, typing help and then press [Enter]. It does not print hello as expected. Thanks!

def foo():
    print('hello')


class Console:
    def __init__(self):
        """Console like interface for navigating and interacting with the external file system."""
        parser = argparse.ArgumentParser(
            description='Console like interface for navigating and interacting with the external file system.',
            add_help=False)
        subparsers = parser.add_subparsers(dest='command')
        subparsers.required = True

        help_parser = subparsers.add_parser('help')
        help_parser.add_argument('-x', type=int, default=1)
        help_parser.set_defaults(func=foo)

        setting_parser = subparsers.add_parser('settings')
        setting_subparsers = setting_parser.add_subparsers(dest='settings_command')
        setting_subparsers.required = True

        setting_save_parser = setting_subparsers.add_parser('save', help='Save the current settings in a .json file.')
        setting_save_parser.add_argument('file', type=str, nargs='?', default='settings.json')

        setting_load_parser = setting_subparsers.add_parser('load', description='Load the last settings from a .json file.')
        setting_load_parser.add_argument('file', type=str, nargs='?', help='settings.json')

        setting_set_parser = setting_subparsers.add_parser('set')
        setting_set_parser.add_argument('--host', type=str, required=True)
        setting_set_parser.add_argument('-u', '--username', type=str, required=True)
        setting_set_parser.add_argument('-p', '--password', type=str, required=True)
        setting_set_parser.add_argument('-x', '--proxy', type=str, required=False)

        while True:
            try:
                print('', flush=True, sep='')
                data = input('>>>').split(' ')
                print('your command:', data)
                parser.parse_args(data)
            except SystemExit:
                pass

if __name__ == '__main__':
    """Spawn an commandline like interface."""
    c = Console()

推荐答案

实际上 argparse 不会自动调用该方法——你必须自己做.它所做的只是将方法添加到 args 的 func 属性中.因此,您可以做的是检查 func 属性是否存在,然后按如下方式调用它:

Actually argparse won't call the method automatically - you have to do it yourself. All it does it adds the method to the func attribute of the args. So, what you could do is to check if func attribute exists and then invoke it as following:

args = parser.parse_args(data)
if hasattr(args, 'func'):
    args.func()

这篇关于python 3 argparse调用一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆