在Python 2.7中使用argparse我试图通过不重复代码和使用代码进行重用来减少我的代码。在这种情况下,我试图重用给予不同子分析器的参数。但是,我收到的错误可能与我试图调用/分配属性的方式有关:
import argparse
def create_args():
parser = argparse.ArgumentParser(description='Transfer file between accounts.'
'Add/remove tabs and Schemas')
subparser = parser.add_subparsers(help='Transfer file between acconts')
transfer = subparser.add_parser('transfer',
help="Transfer file from 2 accounts")
add_arguments(transfer, "producer", "consumer", "uuid")
return parser
def add_arguments(group, *args):
options = group.add_argument_group("Switches")
choices = {
"producer" : ('-p',
'--producer',
'required=True',
'help="Producer\'s(source account)"'),
"consumer" : ('-c',
'--consumer',
'required=True',
'help="Consumer\'s(destination account)"'),
"uuid" : ('-u',
'--uuid',
'required=True',
'help="file ID number"')}
for arg in args:
options.add_argument(choices[arg])
one@dash ~/image_transfer $ python transfer.py transfer
Traceback (most recent call last):
File "transfer.py", line 19, in <module>
start()
File "transfer.py", line 12, in start
args = vars(parser.parse_args())
File "/usr/lib/python2.7/argparse.py", line 1688, in parse_args
args, argv = self.parse_known_args(args, namespace)
File "/usr/lib/python2.7/argparse.py", line 1720, in parse_known_args
namespace, args = self._parse_known_args(args, namespace)
File "/usr/lib/python2.7/argparse.py", line 1929, in _parse_known_args
stop_index = consume_positionals(start_index)
File "/usr/lib/python2.7/argparse.py", line 1885, in consume_positionals
take_action(action, args)
File "/usr/lib/python2.7/argparse.py", line 1794, in take_action
action(self, namespace, argument_values, option_string)
File "/usr/lib/python2.7/argparse.py", line 1090, in __call__
namespace, arg_strings = parser.parse_known_args(arg_strings, namespace)
File "/usr/lib/python2.7/argparse.py", line 1706, in parse_known_args
if not hasattr(namespace, action.dest):
TypeError: hasattr(): attribute name must be string
def start():
parser = create_args()
args = vars(parser.parse_args())
if __name__ == "__main__":
start()
答案 0 :(得分:2)
您可能想看看这个:
choices = {..
"producer" : (
('-p', '--producer'),
{'required':True, 'help': "Producer\'s(source account)"}
),
"consumer" : (
('-c', '--consumer'),
{'required':True, 'help': "Consumer\'s(destination account)"}
),
"uuid" : (
('-u', '--uuid'),
{'required':True, 'help': "file ID number"}
)
}
for arg in args:
options.add_argument(*choices[arg][0], **choices[arg][1])
add_argument
的方法签名如下所示:
add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])
名称或标记部分作为*args
收到,因此其他所有内容都必须命名。您通过使用**kwargs
扩展字典来传递命名args。在你的情况下,你传递一个元组,它试图使用它(因为它是一个单一的参数)作为name or flag
并且错误。