正如其他人回答的那样,optparse是最好的选择,但是如果您只想快速编写代码,请尝试以下操作:
import sys, refirst_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 = ()# ... anywhere in pre ...if 'debug' in args: print 'debug flag'if 'xls' in args: print 'xls flag'编辑 :这是一个optparse的示例,因为这么多的人在回答optparse时并没有真正解释原因,也没有解释要使其正常工作必须进行的更改。
使用optparse的主要原因是,它为您提供了更高的灵活性以供以后扩展,并为您提供了更多的命令行灵活性。换句话说,您的选项可以按任何顺序出现,并且使用信息会自动生成。但是,要使其与optparse一起使用,您需要更改规范,以在可选参数前面加上“-”或“-”,并且需要允许所有参数以任何顺序排列。
因此,这是使用optparse的示例:
import sys, re, optparsefirst_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与您的规范之间的区别在于,现在您可以拥有以下命令行:
python script.py --debug --xls 001
您可以通过调用parser.add_option()轻松添加新选项



