Package ivs :: Package aux :: Module argkwargparser
[hide private]
[frames] | no frames]

Source Code for Module ivs.aux.argkwargparser

 1  """ 
 2  Automatically parse command line args and kwargs. 
 3   
 4  This module is meant to facilitate the translation of command line arguments to 
 5  Python code to parse to methods. 
 6   
 7  Example usage: 
 8   
 9  Given an example minimalistic Python module 'example.py' 
10   
11  >>> def testfunc(a,b,calc='sum'): 
12  >>> ... if calc=='sum': return a+b 
13  >>> ... elif calc=='prod': return a*b 
14  >>> ... return None 
15   
16  >>> if __name__=="__main__": 
17  >>> ... method,args,kwargs = argkwargparser.parse() 
18  >>> ... output = globals()[method](*args,**kwargs) 
19   
20  Then, in a terminal, you can do:: 
21   
22      $:> python example.py testfunc 3 4 
23      7 
24      $:> python example.py testfunc 3 4 calc=prod 
25      12 
26   
27  You can mix args and kwargs, they will be sorted by L{parse}. You can give lists 
28  and more sophisticated input for args and kwargs, see L{parse}. 
29   
30  """ 
31  import json 
32  import sys 
33       
34 -def parse(argv=None):
35 """ 36 Command-line to method call arg processing. 37 38 - positional args: a b -> method('a', 'b') 39 - intifying args: a 123 -> method('a', 123) 40 - json loading args: a '["pi", 3.14, null]' -> method('a', ['pi', 3.14, None]) 41 - keyword args: a foo=bar -> method('a', foo='bar') 42 - using more of the above 1234 'extras=["r2"]' -> method(1234, extras=["r2"]) 43 44 @param argv: Command line arg list. Defaults to `sys.argv`. 45 @return: method-name, args, kwargs 46 @rtype: string, list, dict 47 """ 48 if argv is None: 49 argv = sys.argv 50 51 method_name, arg_strs = argv[1], argv[2:] 52 args = [] 53 kwargs = {} 54 for s in arg_strs: 55 #-- keyword argument if '=' in string 56 if s.count('=') == 1: 57 key, value = s.split('=', 1) 58 #-- maybe the user preceded the keyword with '--' out of habit. In 59 # that case remove it 60 if key[:2]=='--': 61 key = key[2:] 62 #-- normal argument 63 else: 64 key, value = None, s 65 try: 66 value = json.loads(value) 67 except ValueError: 68 pass 69 if key: 70 kwargs[key] = value 71 else: 72 args.append(value) 73 return method_name, args, kwargs
74
75 -def test(*args,**kwargs):
76 print 'args',args 77 print 'kwargs',kwargs
78 79 if __name__=="__main__": 80 method,args,kwargs = parse() 81 out = globals()[method](*args, **kwargs) 82 sys.exit(out) 83