这里是Python新手。 我试图在 argparse 中设置一个参数,其形式为“-x option=value -x option2=value...”
我正在使用以下内容来传递参数。
swlist_parser.add_argument("-x", nargs="+",action='append',metavar='option',
help="-x option=value, set the option to value")
我有一个可用于该命令的默认参数字典。 我想使用 -x option=value 与命令行上的默认参数字典一起修改。
swlist -x distribution_target_directory=/tmp -x admin_directory=/var/lib/sw -x another_option=another_value ...
# Code I have
# args.x is now the following:
if args.x != None:
print("-x options passed: ")
cliopts = {}
for opt in (args.x):
print(opt)
-x 选项已通过: ['distribution_target_directory=/tmp'] ['admin_directory=/var']
-x 的参数现在是类“list”。我需要一个解决方案将它们添加到字典中。
我尝试将 argparse 修改为字典。此选项不允许 option=value
swlist_parser.add_argument("-x", nargs="+",action='append',type=dict,metavar='option', help="-x option=value, set the option to value")
swlist.py -x distribution_target_directory=/tmp -x admin_directory=/var -X /home/pweber/pauls.defaults
用法:swlist [选项] [software_selections] [@target_selections] swlist:错误:参数-x:无效的字典值:'distribution_target_directory = / tmp'
预期的输出将允许此代码将选项添加到字典中
if args.x != None:
print("-x options passed: ")
cliopts = {}
for opt in (args.x):
# convert option=value to dictionary`your text`
cliopts = cliopts|<opt converted to dict>
一旦您有了一个列表
ls
,其中条目由 =
分隔,您可以执行以下操作:
{x.split('=')[0]:x.split('=')[1] for x in ls if len(x.split('='))==2 }
使用列表推导创建字典。