Easier Way to Write Python Console Programs (do args exist)
So I have some code that has way too many of these in it
try:
if argv[4]:
n = argv[4]
except I开发者_如何学JAVAndexError, e:
n = raw_input("Enter n: ")
Is there some easier way to do this?
Basically a better way to check for input to exists and then if it doesn't act accordingly.
Thanks
Have a look at the argparse
module (which does a lot more than is shown here):
import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
const=sum, default=max,
help='sum the integers (default: find the max)')
args = parser.parse_args()
print args.accumulate(args.integers)
You can use len()
to get the length of a sequence such as sys.argv
.
I use plac library - it's easiest way for me. You just have to define a function with some arguments:
import plac
def main(arg1, arg2, arg3=None, arg4='default value'):
print locals()
if __name__ == '__main__':
plac.call(main)
And whe you call your script like this:
$ python my_console_program.py 111 222
you get command line arguments as function arguments:
{'arg1': '111', 'arg2': '222', 'arg3': None, 'arg4': 'default value'}
You can easily handle default and required arguments, options etc.
You could define a wrapper function.
Depending on the complexity of your command-line arguments and the version of Python you're using, you could try the argparse module (available in Python 2.7).
Description in Python Docs:
The argparse module makes it easy to write user friendly command line interfaces. The program defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv. The argparse module also automatically generates help and usage messages and issues errors when users give the program invalid arguments.
精彩评论