場景:手動執行bat文件正常,schtasks定時執行bat文件時報錯。
原因:定時執行時,ini配置文件找不到。Windows 下用 schtasks 定時執行腳本的默認起始路徑為:C:\Windows\System32
解決方法:
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 + "\dbMonitor\config.ini"): #做個判斷,避免上述缺點 self._config.read(batPath + "\dbMonitor\config.ini") else: self._config.read(batRunningPath + "\config.ini") #end