Parsing Unrepresented Arguments

Is there any library that can parse random key pairs in sys.argv in Python?

For example:

python run.py --v1 k1 --v2 k2 --v3 k3 

Should return a dictionary like {v1-> k1, v2-> k2, v3-> k3} to me. and at compile time I don’t know what β€œv” is.

Thanks!

Erben

+1
python argparse
source share
3 answers

These are hackers, but you have this:

 import argparse import collections parser = argparse.ArgumentParser() known, unknown_args = parser.parse_known_args() unknown_options = collections.defaultdict(list) key = None for arg in unknown_args: if arg.startswith('--'): key = arg[2:] else: unknown_options[key].append(arg) 
0
source share
 d = {} for i,arg in enumerate(sys.argv): if arg.startswith("--"): d[arg[2:]] = sys.argv[i+1] print d 
0
source share

In the newer Python, which uses dictionary understanding, you can use one liner as follows:

 ll = sys.argv[1:] args = {k[2:]:v for k,v in zip(ll[::2], ll[1::2])} # {'v1': 'k1', 'v2': 'k2', 'v3': 'k3'} 

This has no flexibility in case your user screws up pairing, but it will be a quick start.

The generator can be used to pop a couple of lines with sys.argv[1:] . This would be a good place for flexibility and error checking.

 def foo(ll): ll = iter(ll) while ll: yield ll.next()[2:], ll.next() {k:v for k,v in foo(ll)} 
0
source share

All Articles