を使用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:])
Getoptions::Long
理想的には、Perlのように、オプションをブール値として定義すると、それに応じてブール値変数cleanup
が自動的に提供さ--cleanup
れ、設定されるようなことをしたいと思います。--no-cleanup