Method 1:
Python has a class that can specialize in command-line arguments, first looking at the code:
# !/usr/bin/env python # encoding:utf-8 from Import
Parser = Optionparser (Usage= " %prog [options] " )
parser.add_option ( " -m " , " --machine ", Action= store ", type= " string ", Dest=" Machine , Help=" the machine to be check " )
(Options,args)=Parser.parse_args () if options.machine: Print Options.machine
The first line is used to initialize,
-M is the parameter shorthand,-machine is the full parameter store meaning that the parameter is stored as type. Dest to which variable to store, the default is the full parameter name, Help is the content to display when helping
Method 2:
Use the Getopt module to parse
ImportSYSImportgetoptdeftestgetopt ():Try: opts, args= Getopt.getopt (sys.argv[1:],'d:f:h',['days=','files=',' Help']) exceptgetopt. Getopterror:usage () sys.exit ( )Print(opts)Print(args) forO, ainchopts:ifOinch("- H","--help"): Usage () sys.exit ()elifOinch("- D","--days"): Day=aelifOinch("- F","--files"): Files=aPrint(Day)Print(Files)
See also: http://blog.csdn.net/lwnylslwnyls/article/details/8199454
Python command-line argument parsing