ConfigParser.NoSectionError: No section: 'MongoDB'

场景:手动执行bat文件正常,schtasks定时执行bat文件时报错。

原因:定时执行时,ini配置文件找不到。Windows 下用 schtasks 定时执行脚本的默认起始路径为:C:WindowsSystem32

解决方法:

import os

  self._config = ConfigParser.SafeConfigParser()
      batRunningPath = os.path.dirname(os.sys.executable) #获取可执行的bat文件所在路径,缺点:手动执行时,获取的是python的安装路径,而不是可执行bat文件所在的路径。
      batPath = os.path.dirname(os.sys.path[0])      #获取可执行的bat文件所在路径的上一级路径,缺点:文件所在文件夹名字写死了(dbMonitor)不能更改。
      if os.path.exists(batPath + "dbMonitorconfig.ini"):  #做个判断,避免上述缺点
          self._config.read(batPath + "dbMonitorconfig.ini")
      else:
          self._config.read(batRunningPath + "config.ini")

  #end

  

原文地址:https://www.cnblogs.com/SZxiaochun/p/6402197.html