我想添加警告和关键警报条件if inputfile == "android": pass,然后检查存储在变量e and f中的数字,并检查它是否处于正常、警告或临界级别,作为我们传递的任何参数。其次,这个脚本在python3.6中运行时没有输出
#!/usr/bin/python
import requests, os, json, sys, getopt
f = 10
e = 20
def main(argv):
inputfile = ''
try:
opts, args = getopt.getopt(argv,"hi:o:w:c:",["ent","lable","help","warning","critical"])
except getopt.GetoptError:
print ("Usage: test.py -i <inputfile>")
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print ("test.py -i <inputfile>")
sys.exit()
# elif opt in ("-i", "--app"):
elif opt == '-i':
inputfile = arg
if inputfile == "android":
'''call a function here (hiding sensitive information) Using e and f variable instead'''
print ("Input is"), inputfile
print("Active:"), f
else:
print("Parameter not found")
sys.exit(2)
# elif opt in ("-o", "--lable"):
elif opt == '-o':
inputfile = arg
print("Active:"), e
if __name__ == "__main__":
main(sys.argv[1:])现在:#python script -i android
输出
Active: 10
预期:
#python script -i android -w 5 -c 20
输出
WARNING - Active: 10
发布于 2018-09-15 13:07:19
sys.argv是list of str。如果要与存储在e和f中的f进行比较,则需要在解析期间转换命令行参数:
if opt == '-i':
input_file = arg
elif opt == '-w':
w_value = int(arg)
elif opt == '-c':
c_value = int(arg)这将允许以后验证它们:
if input_file == 'android':
if w_value < e:
sys.exit('WARNING - w value is too small')
elif c_value > f:
sys.exit('WARNING - c value is too big')原始答案
您可能想看看Python的logging模块。
为了让你开始:
import logging
e = 10
f = 20
logging.basicConfig(level=logging.DEBUG)
logging.log(e, 'This is debug output')
logging.log(f, 'This is an info')这就产生了:
DEBUG:root:This is debug output
INFO:root:This is an info要从那里继续,您可能希望通过将format关键字传递给basicConfig()来影响输出的格式。
e = 30 # logging.WARNING
f = 40 # logging.ERROR
input_file = 'android'
logging.basicConfig(level=logging.DEBUG, format='%(levelname)s - %(message)s')
logging.log(e, 'Input file is "%s"', input_file)
logging.log(f, '"-o" flag detected')这将产生:
WARNING - Input file is "android"
ERROR - "-o" flag detected希望这能回答你的问题,dtk
附带说明:就个人而言,我更喜欢使用argparse而不是getopt。( Fwiw )
https://stackoverflow.com/questions/52344812
复制相似问题