本代码演示了python如何接受命令行参数
##Chris Hall 9/13/11 def main(argv): sys.path.append('models') #Usage will display when the user asks for help (-h) or when something #invalid is entered. The letters used (-c, -n etc) were what I needed for #my project and can be any designator usage = """ Usage: main [-h] [-c] [-l] [-m] [-i] -h help -c command line processing -n no labels put on the screen -l file location 1 -m file location 2 -i file location 3 """ #Set up variables that will be used to store the arguments receive from #command line file1,file2,file3 = None,[],None modellist = [] commandline = False #Get the options and arguments from the command line. getopt takes in what #is to be read (argv) and then the short names #along with the long names that cane be passed. The letters with the ":" #after them designate a required argument entry. try: opts, args = getopt.getopt(argv,"hcnl:m:i:",["help","command","labels", "file1","file2","file3"]) #If an error occurs spit out the proper usage and quit except getopt.GetoptError: print usage sys.exit(0) #Processing of arguments, "o" being the option which relates to our letters #above, and "a" being what was entered by the user for o, a in opts: if o in ("-h", "--help"): print(usage) sys.exit(0) elif o in ("-c", "--command"): commandline = True elif o in ("-n", "--labels"): labels = False elif o in ("-l", "--file1"): file1 = a elif o in ("-m", "--file2"): modellist.append(a) elif o in ("-i", "--file3"): file3 = a #Determine assignment of the 3 required fields if no options provided and #parameters are still passed if args: for arg in args: if arg.endswith(".xml"): file1 = arg if arg.endswith(".py"): modellist.append(arg) if arg.endswith(".txt"): file3 = arg