Wiki source for PythonCommandLine


Show raw source

=====Python on the Command Line=====
return to DevPython

====python from command line====
python -c <command>
%%
# Example to check version of pyodbc module installed
$ python -c "import pyodbc; print pyodbc.version"

# output
2.1.6-beta0
%%

====getopt====
see [[http://code.google.com/p/klenwell/source/browse/trunk/projects/python/boilerplate/getopt.py getopt.py]]
%%
import sys, getopt

def parse_command_line():
"""
add usage text here
"""
optdict = {
'args' : [],
'arg_required' : False, # a:
'not_required' : False, # n
'required' : False, # r
'foo' : 'bar', # foo=
}

try:
args = sys.argv[1:]
optlist, args = getopt.getopt(args, 'a:nr', ['foo='])
except:
sys.stderr.write(parse_command_line.__doc__)
sys.exit(1)

for opt,val in optlist:
if opt == '--foo':
optdict['foo'] = val
elif opt == '-a':
optdict['arg_required'] = val
elif opt == '-n':
optdict['not_required'] = True
elif opt == '-r':
optdict['required'] = True

optdict['args'] = args

if not optdict['arg_required'] or not optdict['required']:
f = "\n\t-a=<val> and -r parameters required to run\n%s\n"
sys.stderr.write(f % (parse_command_line.__doc__))
sys.exit(1)

return optdict

optdict = parse_command_line()
print optdict

# example
klenwell@local:~/tmp $ python parseopt.py -a ok -rn two args
{'arg_required': 'ok', 'foo': 'bar', 'args': ['two', 'args'], 'not_required': True, 'required': True}
%%

====References====
http://docs.python.org/library/getopt.html
Valid XHTML 1.0 TransitionalValid CSSWikkaWiki