type=dict in argparse.add_argument()

后端 未结 11 715
既然无缘
既然无缘 2020-12-03 07:02

I\'m trying to set up a dictionary as optional argument (using argparse); the following line is what I have so far:

parser.add_argument(\'-i\',\'--image\', t         


        
11条回答
  •  囚心锁ツ
    2020-12-03 07:37

    For completeness, and similarly to json.loads, you could use yaml.load (available from PyYAML in PyPI). This has the advantage over json in that there is no need to quote individual keys and values on the command line unless you are trying to, say, force integers into strings or otherwise overcome yaml conversion semantics. But obviously the whole string will need quoting as it contains spaces!

    >>> import argparse
    >>> import yaml
    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('-fna', '--filename-arguments', type=yaml.load)
    >>> data = "{location: warehouse A, site: Gloucester Business Village}"
    >>> ans = parser.parse_args(['-fna', data])
    >>> print ans.filename_arguments['site']
    Gloucester Business Village
    

    Although admittedly in the question given, many of the keys and values would have to be quoted or rephrased to prevent yaml from barfing. Using the following data seems to work quite nicely, if you need numeric rather than string values:

    >>> parser.add_argument('-i', '--image', type=yaml.load)
    >>> data = "{name: img.png, voids: 0x00ff00ff, '0%': 0xff00ff00, '100%': 0xf80654ff}"
    >>> ans = parser.parse_args(['-i', data])
    >>> print ans.image
    {'100%': 4161164543L, 'voids': 16711935, 'name': 'img.png', '0%': 4278255360L}
    

提交回复
热议问题