如何在python中使用getopt.getopt方法?

时间:2018-09-15 12:44:25

标签: python

我想添加警告和严重警报条件if inputfile == "android":,然后检查存储在变量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

1 个答案:

答案 0 :(得分:0)

sys.argvlist中的str。如果要与存储在inte中的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

PS另外,我个人更喜欢使用argparse而不是getopt。 Fwiw;)