捕获变量中的开关到 Argparse
Capture switch in a avriable via Argparse
有没有办法使用 Argparse 来捕获开关及其值作为单独的参数?
即
python MyScript.py --myswitch 10 --yourswitch 'fubar' --herswitch True
…结果类似于…
MyScript.var1 == myswitch
MyScript.var2 == 10
MyScript.var3 == yourswitch
MyScript.var4 == 'fubar'
MyScript.var5 == herswitch
MyScript.var6 == True
……或……
{'myswitch':10, 'yourswitch':'fubar', 'herswitch':True}
=== 编辑 ===
这只使用了 sys.argv。有没有办法用 argparse 做到这一点。即使有办法,使用 argparse 有什么好处吗?
def _parse_unknown_args(self, args):
""""""
scriptname = args.pop(0) # Just gets rid of it
args_dict = {}
flags_list = []
key = None
for item in args:
# Must come first as a 'not'
if not item.startswith('-'):
# This means is a value, not a switch
# Try to add. If value was not preceded by a switch, error
if key is None:
# We got what appears t be a value before we got a switch
err = ''.join(["CorrectToppasPaths._parse_unknown_args: ", "A value without a switch was found. VALUE = '", item, "' (", str(args), ")."])
raise RuntimeError(err)
else:
# Add it to the dict
args_dict[key] = item
key = None # RESET!
else: # '-' IS in item
# If there is ALREADY a switch, add to flags_list and reset
if key is not None:
flags_list.append(key)
key = None # RESET!
# Make it a key. always overrides.
key = item
while key.startswith('-'): key = key[1:] # Pop off the switch marker
# Last check. If key is not None here (at end of list)
# It was at the end. Add it to flags
if key is not None: flags_list.append(key)
return args_dict, flags_list
===
bash-3.2# python correct_toppas_paths.py -a -b -c -set1 1 -set2 2 -d -e
args_dict= {'set1': '1', 'set2': '2'}
flags_list= ['a', 'b', 'c', 'd', 'e']
正确编码的 argparse 解析器将生成一个 Namespace
对象,如:
In [267]: args=argparse.Namespace(myswitch='10', yourswitch='fubar', herswitch=True)
测试打印此对象时是个好主意,例如print(args)
In [268]: args
Out[268]: Namespace(herswitch=True, myswitch='10', yourswitch='fubar')
这些参数中的每一个都是一个属性,您可以访问它(前提是名称不奇怪):
In [269]: args.myswitch
Out[269]: '10'
并且文档表明您可以使用 vars
:
轻松地将其转换为字典
In [270]: vars(args)
Out[270]: {'herswitch': True, 'myswitch': '10', 'yourswitch': 'fubar'}
剩下的只是普通的 Python 编码 - 访问对象的属性或 keys/values 字典。
有没有办法使用 Argparse 来捕获开关及其值作为单独的参数?
即
python MyScript.py --myswitch 10 --yourswitch 'fubar' --herswitch True
…结果类似于…
MyScript.var1 == myswitch
MyScript.var2 == 10
MyScript.var3 == yourswitch
MyScript.var4 == 'fubar'
MyScript.var5 == herswitch
MyScript.var6 == True
……或……
{'myswitch':10, 'yourswitch':'fubar', 'herswitch':True}
=== 编辑 ===
这只使用了 sys.argv。有没有办法用 argparse 做到这一点。即使有办法,使用 argparse 有什么好处吗?
def _parse_unknown_args(self, args):
""""""
scriptname = args.pop(0) # Just gets rid of it
args_dict = {}
flags_list = []
key = None
for item in args:
# Must come first as a 'not'
if not item.startswith('-'):
# This means is a value, not a switch
# Try to add. If value was not preceded by a switch, error
if key is None:
# We got what appears t be a value before we got a switch
err = ''.join(["CorrectToppasPaths._parse_unknown_args: ", "A value without a switch was found. VALUE = '", item, "' (", str(args), ")."])
raise RuntimeError(err)
else:
# Add it to the dict
args_dict[key] = item
key = None # RESET!
else: # '-' IS in item
# If there is ALREADY a switch, add to flags_list and reset
if key is not None:
flags_list.append(key)
key = None # RESET!
# Make it a key. always overrides.
key = item
while key.startswith('-'): key = key[1:] # Pop off the switch marker
# Last check. If key is not None here (at end of list)
# It was at the end. Add it to flags
if key is not None: flags_list.append(key)
return args_dict, flags_list
===
bash-3.2# python correct_toppas_paths.py -a -b -c -set1 1 -set2 2 -d -e
args_dict= {'set1': '1', 'set2': '2'}
flags_list= ['a', 'b', 'c', 'd', 'e']
正确编码的 argparse 解析器将生成一个 Namespace
对象,如:
In [267]: args=argparse.Namespace(myswitch='10', yourswitch='fubar', herswitch=True)
测试打印此对象时是个好主意,例如print(args)
In [268]: args
Out[268]: Namespace(herswitch=True, myswitch='10', yourswitch='fubar')
这些参数中的每一个都是一个属性,您可以访问它(前提是名称不奇怪):
In [269]: args.myswitch
Out[269]: '10'
并且文档表明您可以使用 vars
:
In [270]: vars(args)
Out[270]: {'herswitch': True, 'myswitch': '10', 'yourswitch': 'fubar'}
剩下的只是普通的 Python 编码 - 访问对象的属性或 keys/values 字典。