views:

87

answers:

1

Hi.

I am trying to use optparse but I am having a problem.

My script usage would be: script <filename>

I don't intend to add any option string, such as: script -f <filename> or script --file <filename>

Is there any way I can choose not to pass an argument string? Or is there any way I can allow the user to do this:

script -f <filename> 
script --filename <filename>
script <filename>

All of the above with the same consequence?

I know that I can easily do with this with using argv[1] but the thing is that I might need to add command line support later in the project and add that time I would not want to add optparse support all over. That is the reason I want to use optparse.

+1  A: 
import optparse

parser = optparse.OptionParser()
parser.add_option("-f", "--filename", metavar="FILE", dest="input_file", action="append")
options, args = parser.parse_args()
if options.input_file:
    args.extend(options.input_file)

for arg in args:
    process_file(arg)

This will simply use args as a list of input files, but it will append the file names passed as -f or --filename arguments to args so you will get all of them.

Tamás
@Tamas: Can you please explain what `process_file` does?
A A
@Alfred I'm guessing `process_file` is an example subroutine used as a marker of where to put the code that actually uses your `<filename>` input.
Peter Farmer
@Peter: Aha! Thanks. Stupid me :)
A A