python-如果我指定用户名,为什么我的getopts失败?

我正在编写的第一个功能化python脚本出现问题,下面列出了可以正常使用的摘录.

我的问题是,如果我包括用户名命令行选项(-u或–username),则该选项始终为空,并弄乱了其他命令行参数.

例如,如果我使用-n tdelane -s 10.1.213.226 -p xxx -v的命令行参数来运行它,则将其作为输出:

cliloc = /usr/local/bin/cli
server = 
username = Administrator
password = 
verbose = True
o = -n
a = 
cliloc = /usr/local/bin/cli
server = 
username = 
password = 
verbose = True

如您所见,一旦它到达-n,它不仅将其设置为空,而且也不会处理其他任何事情.如果我取出-n,则可以.使用-s 10.1.213.226 -p xxx -v运行,这是输出:

cliloc = /usr/local/bin/cli
server = 
username = Administrator
password = 
verbose = True
o = -s
a = 10.1.213.226
o = -p
a = xxx
o = -v
a = 
cliloc = /usr/local/bin/cli
server = 10.1.213.226
username = Administrator
password = xxx
verbose = True

这是此脚本中与之相关的部分:

import subprocess, getopt, sys, re

try:
    opts, args = getopt.getopt(sys.argv[1:], "cs:np:hv",                 
        ["cli", "server", "username", "password", "help", "verbose"])

except getopt.GetoptError as err:
    print str(err)
    usage()
    sys.exit(2)

cliloc = '/usr/local/bin/cli'
server = ''
username = 'Administrator'
password = ''
verbose = True

if verbose:
    print "cliloc = %s" % (cliloc)
    print "server = %s" % (server)
    print "username = %s" % (username)
    print "password = %s" % (password)
    print "verbose = %s" % (verbose)

for o, a in opts:
    if verbose:
        print 'o = ' + o
        print 'a = ' + a
    if o == "-v":
        verbose = True
    elif o in ("-h", "--help"):
        usage()
        sys.exit()
    elif o in ("-c", "--cli"):
        cliloc = a
    elif o in ("-s", "--server"):
        server = a
    elif o in ("-n", "--username"):
        username = a
    elif o in ("-p", "--password"):
        password = a
    else:
        assert False, "unhandled option"

if verbose:
    print "cliloc = %s" % (cliloc)
    print "server = %s" % (server)
    print "username = %s" % (username)
    print "password = %s" % (password)
    print "verbose = %s" % (verbose)

提前致谢!

解决方法:

您将-n配置为不带参数;之后没有:

opts, args = getopt.getopt(sys.argv[1:], "cs:np:hv", 
#                                            ^ no colon after this option                
    ["cli", "server", "username", "password", "help", "verbose"])

添加冒号:

opts, args = getopt.getopt(sys.argv[1:], "cs:n:p:hv",                 
#                                             ^ insert colon here
    ["cli", "server", "username", "password", "help", "verbose"])

使用冒号,库知道要查找参数,而tdelane并不会最终将所有内容推入未解析的选项列表中:

>>> import getopt
>>> import shlex
>>> args = shlex.split('-n tdelane -s 10.1.213.226 -p xxx -v')
>>> getopt.getopt(args, "cs:np:hv")
([('-n', '')], ['tdelane', '-s', '10.1.213.226', '-p', 'xxx', '-v'])
>>> getopt.getopt(args, "cs:n:p:hv")
([('-n', 'tdelane'), ('-s', '10.1.213.226'), ('-p', 'xxx'), ('-v', '')], [])

请注意,getopt模块相当陈旧和过时.我将改用argparse.

上一篇:关于getopt的一个注意点


下一篇:javascript-String.prototype.trim.call(text)和text.trim()之间的区别