Search code examples
pythonbooleanoptparse

Optparse Python Set Boolean


I'm having a ton of trouble getting optparse to work in python. It is my first time using it, so any help would be greatly appreciated. I read through all the documentation, but even with their examples, it is not working for me. I am trying to use --clean to make a boolean variable equal to true. This is what I have:

desc = "Use this script for fun!"
parser = optparse.OptionParser(description=desc)
parser.add_option('--clean', help='Run cleaner option', dest = 'runclean', default = False, action = 'store_true')
(args, opts) = parser.parse_args()

print opts.runclean

I thought this would set runclean to true, but when I do:

print opts.runclean

I get:

AttributeError: 'list object has no attribute 'runclean'

Any ideas?


Solution

  • You have the return values reversed:

    (args, opts) = parser.parse_args()
    

    should be

    (opts, args) = parser.parse_args()
    

    Everything will then work.