使用
我是这样做的,但它很繁琐且容易出错,特别是由于易于忘记和省略的
理想情况下,我希望能够像Perl中的
optparse
,有没有一种简单的方法来定义负选项,例如 --no-cleanup
?我是这样做的,但它很繁琐且容易出错,特别是由于易于忘记和省略的
None
检查:#!/bin/env python
from __future__ import print_function
import sys
import optparse
def main(argv):
parser = optparse.OptionParser("usage: %prog [options]")
parser.add_option("--no-cleanup",
dest = "cleanup",
action = "store_false",
help = "do cleanup at end?")
(opts, args) = parser.parse_args()
if opts.cleanup == None:
opts.cleanup = True
# do stuff ...
if opts.cleanup:
print("Cleaning up!", file = sys.stderr)
else:
print("Not cleaning up", file = sys.stderr)
if __name__ == "__main__":
main(sys.argv[1:])
理想情况下,我希望能够像Perl中的
Getoptions :: Long
一样做一些事情,其中我可以将选项cleanup
定义为布尔值,然后它将自动提供--cleanup
和--no-cleanup
,并相应地设置我的布尔变量。
easy_install argparse
命令对我来说一直可以正常工作。 - mgilsonNone
时使用is
运算符是更好的实践,因为None
是单例。(这样重载__eq__
的用户定义类保证不会评估为True
) -- 换句话说,myclassinstance == None
可能是True
,而myclassinstance is None
永远不会。 - mgilsonpip-python
安装了 argparse。 - Frank