简体   繁体   English

Python Argparser显示instancemethod的解析器

[英]Python Argparser show parser from instancemethod

Still plugging away at Python so I will apologize if this comment seems a little too juvenile but I am still having issues figuring this out: 仍然不使用Python,因此如果这个评论看起来过于幼稚,我将道歉,但我仍然无法解决这个问题:

I have a subparser 'foo' and a parser 'test', I will include an abbreviated code snippet below: 我有一个子解析器“ foo”和一个解析器“ test”,下面将包含一个简短的代码片段:

my_parser = test_subparsers.add_parser('foo') my_parser = test_subparsers.add_parser('foo')

my_parser.set_defaults( func =myfunction, which ='Foo') my_parser.set_defaults(func = myfunction,which ='Foo')

When I print out the output from: 当我打印输出时:

parser.parse_known_args() parser.parse_known_args()

I get something that looks like this: 我得到的东西看起来像这样:

(Namespace(config = 'config_file_path', func = 'function myfunction at 0x123456>', which = 'Foo') [] ) (命名空间(config ='config_file_path',func ='函数myfunction at 0x123456>',其中='Foo')[])

The type for parser.parse_known_args() is determined to be an 'instancemethod'. parser.parse_known_args()的类型被确定为“实例方法”。

When I try to convert the string to a dictionary object (using 'vars'), I get an empty dictionary, which I wasn't really surprised by, thanks to you informative people on stack overflow! 当我尝试将字符串转换为字典对象(使用'vars')时,我得到了一个空字典,这并不令我感到惊讶,这要归功于您在堆栈溢出方面的知识渊博!

I am trying to retrieve the "which" item in particular (Foo), does anyone know how to do this?? 我正在尝试检索特别是“哪个”项目(Foo),有人知道该怎么做吗?

parse_known_args returns a tuple , the namespace and a list of 'extras' (here empty) parse_known_args返回一个tuplenamespace和“ extras”列表(此处为空)

In [10]: parser.parse_known_args(['foo'])
Out[10]: (Namespace(func=<function myfunction at 0x9da864c>, which='Foo'), [])

So add the [0] to access the namespace 因此,添加[0]以访问名称空间

In [11]: parser.parse_known_args(['foo'])[0]
Out[11]: Namespace(func=<function myfunction at 0x9da864c>, which='Foo')

The usual way of accessing attributes of the namespace 访问名称空间属性的常用方法

In [12]: parser.parse_known_args(['foo'])[0].func
Out[12]: <function __main__.myfunction>

In [13]: parser.parse_known_args(['foo'])[0].which
Out[13]: 'Foo'

As a dictionary: 作为字典:

In [14]: vars(parser.parse_known_args(['foo'])[0])
Out[14]: {'func': <function __main__.myfunction>, 'which': 'Foo'}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM