python - getopt() not enforcing required arguments? -
i'm having problems getopt()
code in script i'm writing simple file manipulation given 2 required parameters (input filename , 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) 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 getopt()
documentation:
options require argument followed colon ('
:
'; i.e., same format unix getopt() uses).
the problem understand it, variables/args followed :
should enforced required ... options i
, o
not being enforced. running snippet garners error 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 doing wrong?
an option followed colon means needs argument. doesn't mean option enforced. should write own code enforce existence of options/arguments.
Comments
Post a Comment