对于使用optparse,我通常会这样做:
从主代码库中分离命令行解析,以实现更好的模块化。
(将处理放在“if”后面)
让Optparse处理您的帮助。
(使用parser.print_help())
使用optparse结构,如果您不喜欢它们,只需自己分析sys.argv即可。
(使用添加选项定义必要的选项)
以下是我如何使用optparse库编写示例:
def main():
print 'Welcome to the main event!'
if __name__ == '__main__':
import optparse
parser = optparse.OptionParser()
parser.add_option("-e", "--eksponentti", dest="eksponentti",
help="This is help for .",
default=None)
parser.add_option("-s", "--siirre", dest="siirre",
help="This is help for .",
default=None)
parser.add_option("-f", "--figu", dest="figu",
help="This is help for .",
default=None)
(options, args) = parser.parse_args()
if options.eksponentti and options.siirre and options.figu:
main()
else:
print "ERROR -- Expected Arguments not given!"
parser.print_help()
在没有必要选项的情况下运行此命令将提供以下输出:
(比我在这里格式化的要漂亮一点…)
ERROR -- Expected Arguments not given! Usage: parm.py [options]
Options:
-h, --help show this help message and exit
-e EKSPONENTTI, --eksponentti=EKSPONENTTI This is help for .
-s SIIRRE, --siirre=SIIRRE This is help for .
-f FIGU, --figu=FIGU This is help for .