正如其他人所回答的那样,optparse是最好的选择,但如果你只想快速编写代码,请尝试像这样:
import sys, re
first_re = re.compile(r'^\d{3}$')
if len(sys.argv) > 1:
if first_re.match(sys.argv[1]):
print "Primary argument is : ", sys.argv[1]
else:
raise ValueError("First argument should be ...")
args = sys.argv[2:]
else:
args = ()
if 'debug' in args:
print 'debug flag'
if 'xls' in args:
print 'xls flag'
编辑: 这里有一个optparse的例子,因为很多人回答了optparse,但没有真正解释为什么要用它,或者解释一下你必须改变什么才能使其工作。
使用 optparse 的主要原因是它在以后进行扩展时更加灵活,并且在命令行上更加灵活。换句话说,您的选项可以以任何顺序出现,并且使用消息是自动生成的。但是,为了使其与 optparse 协同工作,您需要更改规格,将“-”或“--”放在可选参数的前面,并允许所有参数以任何顺序出现。
因此,这里有一个使用 optparse 的例子:
import sys, re, optparse
first_re = re.compile(r'^\d{3}$')
parser = optparse.OptionParser()
parser.set_defaults(debug=False,xls=False)
parser.add_option('--debug', action='store_true', dest='debug')
parser.add_option('--xls', action='store_true', dest='xls')
(options, args) = parser.parse_args()
if len(args) == 1:
if first_re.match(args[0]):
print "Primary argument is : ", args[0]
else:
raise ValueError("First argument should be ...")
elif len(args) > 1:
raise ValueError("Too many command line arguments")
if options.debug:
print 'debug flag'
if options.xls:
print 'xls flag'
这里与optparse和您的规范(spec)不同的地方在于,现在你可以有类似以下的命令行参数:
python script.py --debug --xls 001
你可以通过调用parser.add_option()轻松添加新选项。