尽管异常在配置解析器中被捕获,但错误回溯在python中显示

2024-09-30 19:31:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在从配置文件中获取值。为了确保我的程序能够处理任何可能发生的异常,我在try except块中设置了config read操作,如下所示:

def __getConfigDetails(self):
        try:
            self.username = config.get("plugin_haproxy", 'user')
            self.hostname = config.get("plugin_haproxy", 'host')
            self.filelocation = config.get("plugin_haproxy", 'filepath')

        except ConfigParser.NoOptionError as error:
            logging.error(error)
            print "Error in options Name", error
        except ConfigParser.NoSectionError as error:
            logging.error(error)
            print "Error in sections Name", error

在获得详细信息后,我调用另一个需要上述值作为参数的函数。我们知道其中一个值当然不可用,但是我们如何处理这种情况,为什么异常不处理它

^{pr2}$

程序运行得很好,但是假设如果用户更改了配置文件中的选项,并将用户改为用户名,那么该方法当然可以处理它,因为我们正在处理ConfigParser.NoOptionError例外。在

这里,在我的程序中,它抛出异常,但也抛出错误回溯,如下所示

Traceback (most recent call last):
  File "main.py", line 67, in <module>
    main()
  File "main.py", line 59, in main
    cons.PLUGIN_CONFIG_PATH, finaloutput, finallogs)
  File "/home/tara/taraproject/checkaccessEnv/project2/plugins/plugin_haproxy/plugin_haproxy.py", line 51, in run
    self.__getConfigDetails()
  File "/home/tara/taraproject/checkaccessEnv/project2/plugins/plugin_haproxy/plugin_haproxy.py", line 23, in __getConfigDetails
    self.username = config.get("plugin_haproxy", 'user')
  File "/usr/lib/python2.7/ConfigParser.py", line 340, in get
    raise NoOptionError(option, section)
ConfigParser.NoOptionError: No option 'user' in section: 'plugin_haproxy'

我只想显示例外打印,为什么会这样?在

I know I can handle this situations by using if clause on secondfunction ie, __executeCommand to make sure if it runs than only move further but this might not be the solution since I have exceptions doing the work forhead, What is the best way to solve such problem


Tags: inpyselfconfiggetmainlineerror
1条回答
网友
1楼 · 发布于 2024-09-30 19:31:14

问题是 异常发生了,我获取配置值的try块无法获取它,因为它没有执行,接下来我调用函数 **在

self.executeCommand(self.username, self.hostname, self.filelocation)

对于没有设置值的参数,因此在前面的函数中发生了错误def\u getConfigDetails(self):我添加了系统出口()如下。在

def __getConfigDetails(self):
        try:
            self.username = config.get("plugin_haproxy", 'user')
            self.hostname = config.get("plugin_haproxy", 'host')
            self.filelocation = config.get("plugin_haproxy", 'filepath')
            logging.info('Config Read Success')
        except ConfigParser.NoOptionError as error:
            logging.exception(error)
            print "Error in options Name", error
            sys.exit(1)
        except ConfigParser.NoSectionError as error:
            logging.error(error)
            print "Error in sections Name", error
            sys.exit(1)

我希望这是正确的做法

相关问题 更多 >