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
.
This doesn't answer the direct question, 'how to define an Action...', but it handles the inputs in a simple way.
Set
'-o'
to be'store_true'
. If True check the'args'
variable for a file name.(In
argparse
the equivalent would be to define a positional argument withnargs='?'
.)If these are the only arguments, you could also get by with checking for the filename without requiring the
`-o'
.Another possibility - 'store_const', with the positional 'filename' having priority:
I don't think there is unfortunately - the only way I can think of is hacking around the problem by adding your own logic statements. The following code should do the trick.
You can use optparse-callbacks to achieve this.
Here is how it wiill work for your use case.