Python getopt module raises error when argument is not behind option

I have a piece of code to handle command line arguments.

def parse_cmd_args(): input_path = None output_name = 'out.flv.txt' is_detail = False try: opts, args = getopt.getopt(sys.argv[1:], "hi:o:d") except getopt.GetoptError: print 'Usage:' print 'parse_flv -i input_path -o [output_name]' sys.exit() for op, value in opts: if op == '-i': input_path = value elif op == '-o': output_name = value elif op == '-d': is_detail = True elif op == '-h': print 'Usage:' print 'parse_flv -i input_path [-o output_name]' sys.exit() return os.path.abspath(input_path), output_name, is_detail 

If I enter the command without a option symbol '-' as follows:

  python parse_flv.py s 

This will cause an error.

MY QUESTION :

How to handle arguments without the -i option using the getopt module. Thanks

+4
source share
2 answers

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 # Get input name by yourself... input_name = remainder[0] print 'OUTPUTNAME :', output_name print 'REMAINING :', remainder print 'INPUTNAME :', input_name 

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 .

+5
source

In your code, the argument s is in the args list returned from getopt.getopt() .

+1
source

Source: https://habr.com/ru/post/1488474/


All Articles