Usually, although they are a character sequence, all the arguments when starting a program are making it a special format, and if they change an argument into various models and pass it, they are convenient.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 | import marshal
import pickle
import urllib
class ArgumentConverter:
"Convert a argument to one of some object"
def str_convert(self, arg):
return arg
def int_convert(self, arg):
try: return int(arg)
except: pass
return long(arg)
def long_convert(self, arg):
return long(arg)
def float_convert(self, arg):
return float(arg)
def list_convert(self, arg):
vals = []
for token in arg.split(','):
vals.append(self.convert(token))
return vals
def tuple_convert(self, arg):
return tuple(self.list_convert(arg))
def file_convert(self, arg):
return open(arg)
def marshal_convert(self, arg):
return marshal.load(open(arg))
def pickle_convert(self, arg):
return pickle.load(open(arg))
def uri_convert(self, arg):
return urllib.urlopen(arg)
s_convert = str_convert
i_convert = int_convert
l_convert = long_convert
f_convert = float_convert
L_convert = list_convert
T_convert = tuple_convert
F_convert = file_convert
M_convert = marshal_convert
P_convert = pickle_convert
U_convert = uri_convert
def convert(self, arg):
suffix = 'str' # default suffix
if arg.count(':'):
suffix, value = arg.split(':', 1)
else:
value = arg
return apply(getattr(self, suffix + '_convert'), (value,))
import sys
def getusage():
return '''\
str(s):string String(default)
int(i):int Integer(convert to Long type, if it value is too long)
long(l):long Long
float(f):float Float
file(F):file File object
marshal(M):file Marshalized file object
pickle(P):file Pickled file object
uri(U):uri Opened uri file object
list(L):list List('list:int:1,file:foo' is [1, <file foo>])
tuple(T):tuple Tuple('tuple:int:1,file:foo' is (1, <file foo>))'''
def usage():
print >>sys.stderr, 'Argument synopsis'
print >>sys.stderr, getusage()
def test():
aconv = ArgumentConverter()
if len(sys.argv) < 2:
usage()
sys.exit()
for arg in sys.argv[1:]:
print aconv.convert(arg)
if __name__ == '__main__':
test()
|
Usage is carried out like "type:value" When extending, a method like "type_convert" is only added. For example, when supporting the gzipped file, the method "gzip_convert" is added, file deployment is carried out based on an argument, and it is made to return.
uri_convert: cannot get it to work.
please remove the above comment. thank you
apply()
is deprecated.apply(getattr(self, suffix + '_convert'), (value,))
should be changed togetattr(self, suffix + '_convert')(value)