You should use argparse instead . getopt is limited ...
This module is much more convenient (less code and more informative help and error messages). In your case, it will just be something like:
parser = argparse.ArgumentParser(add_help=True) parser.add_argument('infile', nargs=1, help='input file name') parser.add_argument('outfile', nargs='?', help='output file name')
In this example, outfile will be optional, and you can specify the default output file name:
parser.add_argument('outfile', nargs='?', help='output file name', default='out.txt')
Read more about getopt and argparse here (compared to each other).
EDIT:
Here is the best thing you can do with getopt (as far as I read), i.e. switch to GNU mode with gnu_getopt :
import getopt import sys output_name = 'out.txt' input_name = '' print 'ARGV :', sys.argv[1:] options, remainder = getopt.gnu_getopt(sys.argv[1:], 'o:', ['input-path', 'output-name=', ]) print 'OPTIONS :', options for opt, arg in options: if opt in ('-o', '--output-name'): output_name = arg else: pass
Vocation:
python parse_flv.py input -o output
or
python parse_flv.py -o output input
outputs:
ARGV : ['-o', 'output', 'input'] OPTIONS : [('-o', 'output')] OUTPUTNAME : output REMAINING : ['input'] INPUTNAME : input
which confirms that you have to deal with the remaining list yourself ...
But at least you can switch the order of the two parameters.
An interesting source here .