做网站别人输账号代码/免费外链发布平台
getopt.getopt(args, options[, long_options])
对于短格式options,-号后要紧跟一个选项字母。如果还有此选项的附加参数,可以用空格分开,也可以不分开,长度任意,可以用引号(比如-uroot、-u root、-u"root"、-u’root’、-u “root”、-u ‘root’)。
对于长格式long_options,–号后要紧跟一个单词。如果还有参数要附加,后面要紧跟=,再加上参数,等号前后都不能有空格。
?vrJ:p:u:h:f: 也可以写为 -?-v-r-J:-p:-u:-h:-f:
短格式?、v、r都是开关选项不带参数,J:表示后面需要带参数(后面有:,都需要带参数)
[‘version’, ‘output=’]
长格式没有=号是开关选项不带参数
该函数返回两个列表:opts和args。opts为分析出的格式信息。args为不属于格式信息的剩余的命令行参数,即不是按照getopt()里面定义的长或短选项字符和附加参数以外的信息。opts是一个两元组的列表。每个元素为:(选项串,附加参数)。如果没有附加参数则为空串。
python test1.py ‘-h -o file --help --output= out file1 file2’
opts的输出结果为:[(’-h’,’’),(’-o’,‘file’),(’–help’,’’),(’–output’,‘out’)],而args则为:[‘file1’,‘file2’],这就是上面不属于格式信息的剩余的命令行参数。
短格式不带参数输入时可以缩略写,比如-?vr,命令输出为opts和args
import os
import getopt
#
# all the command line options
#
class Global:script_name = os.path.split(__file__)[-1]USER = os.environ.get('LOGNAME') or os.environ.get('USER')opt = {}opt['-v'] = Falseopt['-h'] = []opt['-f'] = Noneopt['-J'] = '=:'opt['-r'] = FalsefilePath = []GV = Global()#############
def parseCommandLine():try:(options, args) = getopt.getopt(sys.argv[1:], '?vrJ:p:u:h:f:', ['version'])except Exception, e:usage('Error: ' + str(e))for (switch, val) in options:if (switch == '-?'):usage(0)elif (switch == '-v'):GV.opt[switch] = Trueelif (switch == '-f'):GV.opt[switch] = valelif (switch == '-h'):GV.opt[switch].append(val)elif (switch == '-J'):GV.opt[switch] = val + ':'elif (switch == '-r'):GV.opt[switch] = Trueelif (switch == '--version'):print_version()hf = (len(GV.opt['-h']) and 1 or 0) + (GV.opt['-f'] and 1 or 0)if hf != 1:usage('Error: please specify at least one of -h or -f args, but not both')if (len(args) < 2):usage('Error: please specify local and remote file paths')GV.filePath = args