optparse
には、負のオプションを定義する簡単な方法がありますか?たとえば--no-cleanup
?負のブールオプション--no-whoptはoptparseにありますか?
私はこのようにそれをしなかったが、それは面倒なバグが発生しやすい、忘れて、除外することは容易であるNone
チェックに特に原因です:理想的には私はGetoptions::Long
ような何かをしたいと思います
#!/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では、オプションcleanup
をブール値として定義し、次に自動的に--cleanup
と--no-cleanup
を提供し、それに応じてブール変数を設定します。
argparseにはこの機能がありますか、それともオプションではありませんか? – jterrace
@jterrace:Python v2.6を使用しているので、私はargparseを持っていないと思います。 – Frank
@Frank、argparseはPython2.6で動作しますが、標準ライブラリにはありません。もしあなたがsetuptoolsを持っていれば、 'easy_install argparse'はいつもうまくいってくれました。 – mgilson