Python 'getopt' 语法,允许可选的命令行参数,无法识别 longopts

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 或 -p

-- Works properly

$ python myApp.py -纸或--纸

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

大家好。所以我不确定我做错了什么,我的 longopts,“paper”没有被命令行识别。

谢谢。

恭敬地,

Slid3r

您包装这两个语句的 try-except 可能会掩盖错误并使其无法分配选项。我重写了它,所以那些 try-except 语句消失了,并修复了 getopt.

的一些用法

您可能应该考虑返回的元组。根据文档 (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)

最终成品:

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!')

这会导致这些输出:

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

允许起始索引超过长度的切片:

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