Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getopt() not enforcing required arguments?

Tags:

python

I'm having problems with this getopt() code in a script that I'm writing which does some simple file manipulation given 2 required parameters (input filename and output filename) and/or 2 optional/situational arguments (debug or help).

Code is:

def main(argv):
    try:
        opts, args = getopt.getopt(argv, "i:o:dh", ["input-file=", "output-file=", "debug", "help"])
    except getopt.GetoptError:
        usage()
        sys.exit(2)

    for opt, arg in opts:
        if opt in ("-h", "--help"):
            usage()
            sys.exit()
        elif opt in ("-d", "--debug"):
            global _debug
            _debug = 1
        elif opt in ("-i", "--input-file"):
            u_input_file_name = arg
        elif opt in ("-o", "--output-file"):
            u_output_file_name = arg

According to the getopt() documentation:

options that require an argument followed by a colon (':'; i.e., the same format that Unix getopt() uses).

The problem is that as I understand it, the variables/args followed by a : should be enforced as required ... but the options i and o are not being enforced. Running this snippet garners an error about u_input_file_name being referenced before being assigned:

[tdelane@fbsd81-1 ~/python]$ ./inco_add_cm_mpscli.py -o google
Traceback (most recent call last):
  File "./inco_add_cm_mpscli.py", line 57, in <module>
    main(sys.argv[1:])
  File "./inco_add_cm_mpscli.py", line 25, in main
    infile = open(u_input_file_name, 'r')
UnboundLocalError: local variable 'u_input_file_name' referenced before assignment

What am I doing wrong?

like image 231
Tyler D Avatar asked Feb 18 '11 19:02

Tyler D


2 Answers

An option followed by a colon only means that it needs an argument. It doesn't mean that the option is enforced. You should write your own code to enforce the existence of options/arguments.

like image 162
evergreen Avatar answered Oct 22 '22 14:10

evergreen


Just as a note, I found that argparse is simpler and more useful than getopt, and it support required arguments.

http://docs.python.org/2/howto/argparse.html#id1

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("echo", help="echo the string you use here")
args = parser.parse_args()

Command Line

$ python prog.py
usage: prog.py [-h] echo
prog.py: error: the following arguments are required: echo
like image 43
allenhwkim Avatar answered Oct 22 '22 14:10

allenhwkim