Python ‘getopt’ syntax, allowing optional command line arguments, longopts not recognized

import sys
import getopt

paper = 0

try:
    argv = sys.argv[1:]
except:
    pass

try:
    options = getopt.getopt(argv, 'p', ["paper"])
except:
    pass

for name in options:
    if name in ['p', '-p', '-paper', '--paper']:
        paper = 1    

$ python myApp.py p or -p

-- Works properly

$ python myApp.py -paper or –paper

-- Traceback (most recent call last):
File "myApp.py", line 52, in <module>
for name in options:
NameError: name 'options' is not defined

Hey gang. So I am not sure what I am doing wrong that my longopts, “paper” is not being recognized from the command line.

Thank you.

Respectfully,

Slid3r

Answer

The try-except that you have wrapping the two statements is likely masking an error and making it so options isn’t assigned. I’ve rewritten it so those try-except statements are gone, as well as fixing some of the usage with getopt.

You should probably account for the tuple being returned. Per the documentation (https://docs.python.org/3/library/getopt.html#getopt.getopt):

the first is a list of (option, value) pairs; the second is the list of program arguments left after the option list was stripped (this is a trailing slice of args)

The final product:

import sys
import getopt

argv = sys.argv[1:]
options, args = getopt.getopt(argv, 'p', ["paper"])

for opt_value in options:
    if opt_value[0] in ['-p', '--paper']:
        print('Paper arg set!')

which results in these outputs:

~$ python myApp.py --paper
Paper arg set!
~$ python myApp.py -p
Paper arg set!

Slice allowing start index past length:

> myargs = ['myapp.py', 'a', 'b', 'c']
> myargs[5:]
< []

Leave a Reply

Your email address will not be published. Required fields are marked *