views:

692

answers:

4
if __name__=='__main__':
    parser = OptionParser()
    parser.add_option("-i", "--input_file", 
                    dest="input_filename",
                      help="Read input from FILE", metavar="FILE")

    (options, args) = parser.parse_args()
    print options

result is

$ python convert.py -i video_*
{'input_filename': 'video_1.wmv'}

there are video_[1-6].wmv in the current folder. Question is why video_* become video_1.wmv. What i'm doing wrong?

+6  A: 

Python has nothing to do with this -- it's the shell.

Call

$ python convert.py -i 'video_*'

and it will pass in that wildcard.

The other six values were passed in as args, not attached to the -i, exactly as if you'd run python convert.py -i video_1 video_2 video_3 video_4 video_5 video_6, and the -i only attaches to the immediate next parameter.

That said, your best bet might to be just read your input filenames from args, rather than using options.input.

Charles Duffy
+2  A: 

Print out args and you'll see where the other files are going...

They are being converted to separate arguments in argv, and optparse only takes the first one as the value for the input_filename option.

Douglas Leeder
A: 

It isn't obvious, even if you read some of the standards (like this or this).

The args part of a command line are -- almost universally -- the input files.

There are only very rare odd-ball cases where an input file is specified as an option. It does happen, but it's very rare.

Also, the output files are never named as args. They almost always are provided as named options.

The idea is that

  1. Most programs can (and should) read from stdin. The command-line argument of -- is a code for "stdin". If no arguments are given, stdin is the fallback plan.

  2. If your program opens any files, it may as well open an unlimited number of files specified on the command line. The shell facilitates this by expanding wild-cards for you. [Windows doesn't do this for you, however.]

  3. You program should never overwrite a file without an explicit command-line options, like '-o somefile' to write to a file.

Note that cp, mv, rm are the big examples of programs that don't follow these standards.

S.Lott
While your comment is informative, it doesn't remotely answer the question asked.
David Locke
@David Locke: True, I did not use the words "You're doing it wrong". The approach deviates so far from the expectations of the API that it's hard to comment more fully.
S.Lott
A: 

To clarify:

aprogram -e *.wmv

on a Linux shell, all wildcards (*.wmv) are expanded by the shell. So aprogram actually recieves the arguments:

sys.argv == ['aprogram', '-e', '1.wmv', '2.wmv', '3.wmv']

Like Charles said, you can quote the argument to get it to pass in literally:

aprogram -e "*.wmv"

This will pass in:

sys.argv == ['aprogram', '-e', '*.wmv']
Paul Fisher