• 欢迎访问开心洋葱网站,在线教程,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站,欢迎加入开心洋葱 QQ群
  • 为方便开心洋葱网用户,开心洋葱官网已经开启复制功能!
  • 欢迎访问开心洋葱网站,手机也能访问哦~欢迎加入开心洋葱多维思维学习平台 QQ群
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏开心洋葱吧~~~~~~~~~~~~~!
  • 由于近期流量激增,小站的ECS没能经的起亲们的访问,本站依然没有盈利,如果各位看如果觉着文字不错,还请看官给小站打个赏~~~~~~~~~~~~~!

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

python 水墨上仙 1353次浏览

本代码演示了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


开心洋葱 , 版权所有丨如未注明 , 均为原创丨未经授权请勿修改 , 转载请注明python开发控制台程序的参数传递方法
喜欢 (0)
加载中……