Search code examples
pythonactionstoreargparseoptparse

Python: Can optparse have the ACTION attribute to act both like STORE and STORE_TRUE?


I am using optparse to get command line input.

Lets say that I am running a script demo.py and it creates some output. But unless I specify the command line input, the output is not written to a file.

I am trying to do the following:

python demo.py in command line should run the script, but not write the output anywhere.

python demo.py -o in command line should write the output to my default file name output.txt.

python demo.py -o demooutput.txt in command line should write the output to file demooutput.txt.

PS: I would not prefer to switch to argparse from optparse.


Solution

  • You can use optparse-callbacks to achieve this.

    Here is how it wiill work for your use case.

    parser.add_option("-o", action="callback", dest="output", callback=my_callback)
    
    def my_callback(option, opt, value, parser):
         if len(parser.rargs) > 0:
             next_arg = parser.rargs[0]
             if not next_arg.startswith("-"):
                 # Next argument is not another option
                 del parser.rargs[0]
                 setattr(parser.values, option.dest, next_arg)
                 return
         # If not processed, set the default value
         setattr(parser.values, option.dest, "output.txt")