我无法将参数传递给我的脚本。 脚本启动命令行:myscript.py -c随机 我在我的代码中使用了getopt(在那里给出)但是这段代码没有循环遍历参数,因为稍后在程序中没有定义tests_company varible,我哪里出错?
tested_company=None
try:
opts, args = getopt.getopt(sys.argv[1:], "hc:i", ['help', 'company', 'info']) #first argument ignored because zabbix giving it and being useless
except getopt.GetoptError as e:
print (e)
usage()
sys.exit(3)
if not opts:
#print ('No options supplied, only updating the database')
print("3")
sys.exit(3)
else:
for opt, arg in opts:
if opt in ('-h', '--help'):
usage()
sys.exit(0)
elif opt in ('-c', '--company'):
tested_company = arg
elif opt == '-i':
displayInfos=1
答案 0 :(得分:2)
我认为您在getopt调用中company
之后错过了一个等号。这段代码适合我:
import getopt
import sys
tested_company=None
try:
opts, args = getopt.getopt(sys.argv[1:], "hc:i", ['help', 'company=', 'info']) #first argument ignored because zabbix giving it and being useless
print(opts)
except getopt.GetoptError as e:
print (e)
usage()
sys.exit(3)
if not opts:
#print ('No options supplied, only updating the database')
print("3")
sys.exit(3)
else:
for opt, arg in opts:
if opt in ('-h', '--help'):
usage()
sys.exit(0)
elif opt in ('-c', '--company'):
tested_company = arg
elif opt == '-i':
displayInfos=1
print(tested_company)
用
调用它> python .\script.py -c xxxx
给出
[('-c', 'xxxx')]
xxxx
使用
进行通话> python .\script.py --company xxxx
给出
[('--company', 'xxxx')]
xxxx
答案 1 :(得分:1)
opts变量可能无法初始化,而是在try语句之外调用。你不能做以下任何特殊原因?
tested_company=None
try:
opts, args = getopt.getopt(sys.argv[1:], "hc:i", ['help', 'company', 'info']) #first argument ignored because zabbix giving it and being useless
if not opts:
#print ('No options supplied, only updating the database')
print("3")
sys.exit(3)
else:
for opt, arg in opts:
if opt in ('-h', '--help'):
usage()
sys.exit(0)
elif opt in ('-c', '--company'):
tested_company = arg
elif opt == '-i':
displayInfos=1
except getopt.GetoptError as e:
print (e)
usage()
sys.exit(3)