[Python] python开发控制台程序的参数传递方法 →→→→→进入此内容的聊天室

来自 , 2021-01-19, 写在 Python, 查看 114 次.
URL http://www.code666.cn/view/3f1656d9
  1. ##Chris Hall 9/13/11
  2. def main(argv):
  3.     sys.path.append('models')
  4.     #Usage will display when the user asks for help (-h) or when something
  5.     #invalid is entered. The letters used (-c, -n etc) were what I needed for
  6.     #my project and can be any designator
  7.     usage = """
  8.    Usage:
  9.        main [-h] [-c] [-l] [-m] [-i]
  10.  
  11.        -h  help
  12.        -c  command line processing
  13.        -n  no labels put on the screen
  14.        -l  file location 1
  15.        -m  file location 2
  16.        -i  file location 3
  17.  
  18.     """
  19.      #Set up variables that will be used to store the arguments receive from
  20.      #command line
  21.     file1,file2,file3 = None,[],None
  22.     modellist = []
  23.     commandline = False
  24.  
  25.     #Get the options and arguments from the command line. getopt takes in what
  26.     #is to be read (argv) and then the short names
  27.     #along with the long names that cane be passed. The letters with the ":"
  28.     #after them designate a required argument entry.
  29.     try:
  30.         opts, args = getopt.getopt(argv,"hcnl:m:i:",["help","command","labels",
  31.         "file1","file2","file3"])
  32.     #If an error occurs spit out the proper usage and quit
  33.     except getopt.GetoptError:
  34.         print usage
  35.         sys.exit(0)
  36.  
  37.     #Processing of arguments, "o" being the option which relates to our letters
  38.     #above, and "a" being what was entered by the user
  39.     for o, a in opts:
  40.         if o in ("-h", "--help"):
  41.             print(usage)
  42.             sys.exit(0)
  43.         elif o in ("-c", "--command"):
  44.             commandline = True
  45.         elif o in ("-n", "--labels"):
  46.             labels = False
  47.         elif o in ("-l", "--file1"):
  48.             file1 = a
  49.         elif o in ("-m", "--file2"):
  50.             modellist.append(a)
  51.         elif o in ("-i", "--file3"):
  52.             file3 = a
  53.  
  54.     #Determine assignment of the 3 required fields if no options provided and
  55.     #parameters are still passed
  56.     if args:
  57.         for arg in args:
  58.             if arg.endswith(".xml"):
  59.                 file1 = arg
  60.             if arg.endswith(".py"):
  61.                 modellist.append(arg)
  62.             if arg.endswith(".txt"):
  63.                 file3 = arg
  64. #//python/2295

回复 "python开发控制台程序的参数传递方法"

这儿你可以回复上面这条便签

captcha