With optparse
, is there a simple way to define negative options, e.g., --no-cleanup
?
I did it this way, but it's cumbersome and bug-prone, especially due to the None
check which is easy to forget and leave out:
#!/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:])
Ideally I'd like to do something like Getoptions::Long
in Perl, where I can define an option cleanup
as boolean and then it will automatically provide --cleanup
and --no-cleanup
and set my boolean variable accordingly.
easy_install argparse
has always worked just fine for me. – Disdainis
operator when testing forNone
sinceNone
is a singleton. (That way user defined classes which override__eq__
are guaranteed to not evaluate toTrue
) -- in other wordsmyclassinstance == None
could potentially beTrue
whereasmyclassinstance is None
will never be. – Disdainpip-python
now. – Danieladaniele