python中的getopt方法不适用于大量参数

问题描述 投票:0回答:1
import getopt
import sys

options, remainder = getopt.getopt(sys.argv[1:], 'a:b:c:d:e:f:g:h', ['aa','bb','cc','dd','ee','ff','gg','hh'])

list=[]  
for opt, arg in options:    
    if opt in ('-a'):  
        list.append(arg.strip())  
    if opt in ('-b'):  
        list.append(arg.strip())  
    if opt in ('-c'):  
        list.append(arg.strip())  
    if opt in ('-d'):  
        list.append(arg.strip())  
    if opt in ('-e'):  
        list.append(arg.strip())  
    if opt in ('-f'):  
        list.append(arg.strip())  
    if opt in ('-g'):  
        list.append(arg.strip())  
    if opt in ('-h'):  
        list.append(arg.strip())
print(list)

对于上面的代码,当我提供命令行参数时:

python mainFile.py -a aa -b bb -c cc -d dd -e ee -f ff -g gg -h hh

输出:

['aa', 'bb', 'cc', 'dd', 'ee', 'ff', 'gg','']

我想要的地方:

['aa', 'bb', 'cc', 'dd', 'ee', 'ff', 'gg', 'hh']

我应该怎么做才能获得所需的输出。

python
1个回答
1
投票

如果您有带有参数的选项,则必须添加:

import getopt
import sys

options, remainder = getopt.getopt(sys.argv[1:], 'a:b:c:d:e:f:g:h:', ['aa','bb','cc','dd','ee','ff','gg','hh'])

list=[]  
for opt, arg in options:    
    if opt == '-a':  
        list.append(arg.strip())  
    if opt == '-b':  
        list.append(arg.strip())  
    if opt == '-c':  
        list.append(arg.strip())  
    if opt == '-d':  
        list.append(arg.strip())  
    if opt == '-e':  
        list.append(arg.strip())  
    if opt == '-f':  
        list.append(arg.strip())  
    if opt == '-g':  
        list.append(arg.strip())  
    if opt == '-h':  
        list.append(arg.strip())
print(list)

[in在这里是错误的,请使用==。最好使用更高级的命令行解析器,例如argparse

© www.soinside.com 2019 - 2024. All rights reserved.