python - How to access argparse key name instead of value? -
a callee.py
has namespace
using argparse
:
parser = namespace(action='run', action_area='park', severity='high') in [30]: parser.action out[30]: 'run'
if type in command line, should enough:
callee.py --run --action_area gym --severity low
if call inside program caller.py
, this:
callee.py sth.run sth.action_area 'gym' sth.severity 'low'
the advantages are: more regulated easier update if args in callee.py
change
i wish sth
came argparse
or not have code myself.
i build sth
this:
class parserkeys(object): def __init__(self, keys): self.keys = keys key in keys: setattr(self, key, '--{0}'.format(key)) sth = parserkeys(vars(parser).keys()) in [91]: sth.action out[91]: '--action'
my question is: there way inside argparse
or other ways not have build class this?
this example explain requirements, how achieve not limited argparse
if feature not available(i assume should).
i sure not first , last 1 requires feature. hope explain time.
the usual way use argparse
define parser, populate 'arguments', , call parse_args()
parse command line.
parse_args()
returns namespace object use.
it possible define namespace object directly:
in [203]: ns = argparse.namespace(x=12, y='abc') in [204]: ns out[204]: namespace(x=12, y='abc') in [205]: ns.x out[205]: 12 in [206]: nx.z .... nameerror: name 'nx' not defined in [207]: ns.z = [1,2,3] in [208]: ns out[208]: namespace(x=12, y='abc', z=[1, 2, 3])
you can add values existing object, can't access values aren't defined. namespace
class simple, adding few methods make display of values prettier.
you can dictionary it:
in [209]: vars(ns) out[209]: {'x': 12, 'y': 'abc', 'z': [1, 2, 3]} in [210]: list(vars(ns).keys()) out[210]: ['z', 'y', 'x']
fetching value using key
string:
in [212]: getattr(ns,'x') out[212]: 12
you can set attributes name
in [220]: setattr(ns,'w','other') in [221]: ns out[221]: namespace(w='other', x=12, y='abc', z=[1, 2, 3])
the method ns
uses display values is:
def __repr__(self): type_name = type(self).__name__ arg_strings = [] arg in self._get_args(): arg_strings.append(repr(arg)) name, value in self._get_kwargs(): arg_strings.append('%s=%r' % (name, value)) return '%s(%s)' % (type_name, ', '.join(arg_strings)) def _get_kwargs(self): return sorted(self.__dict__.items())
self.__dict__
same thing vars(ns)
gives. attributes stored in dictionary (as true objects, user defined ones).
if want more namespace
, or define own class, i'd suggest looking @ class in argparse.py
file. argparse
tries make minimal assumptions nature of class. possible uses getattr
, setattr
functions. , hasattr
well:
in [222]: hasattr(ns, 'foo') out[222]: false in [223]: hasattr(ns, 'w') out[223]: true
from edits sounds want 'recover' option flag attribute names in namespace. is
parser.add_argument('--foo', '-f', ...) parser.add_argument('bar', ...) parser.add_argument('--other', dest='baz',...)
will produce namespace(foo=..., bar=....)
the attribute name called dest
. when saving values parser uses
setattr(namespace, dest, value)
for positional argument dest
1st parameter, 'bar' in above example. optional argument, dest
derived first long parameter, '--foo' above. or may set explicit dest='baz'
parameter.
so adding --
ns.__dict__
key start.
there isn't code in argparse
can recreate commandline parsing results.
Comments
Post a Comment