通过Argparse捕获交换机

时间:2016-10-28 13:42:03

标签: python-2.7 arguments 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']

1 个答案:

答案 0 :(得分:1)

正确编码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编码 - 访问对象的属性或字典的键/值。