[项目实践] 使用相对路径引发的大坑,记一次使用sys.path[0]

python学习网 2018-11-09 09:49:03

下面是一个获取配置的代码

 1     def getValue(self,section,option):
 2         """
 3         @file: string,the name of the config file
 4         @section: string,the name of the section in config file
 5         @option: string,the name of the option in section field
 6         This function will return a int value which the option is specified.
 7         """
 8         try:
 9             configs = ConfigParser()
10              filepath = sys.path[1] + "\\config\\" + self.filename + ".ini" 
11 #             print (filepath)
12             line = configs.read(filepath)
13             result = configs.getint(section, option)
14             return int(result)
15         except Exception as e:
16             print (e)

在实际引用该段代码时,随着在其它模块中进行引用时,经常会发现提示模块不存在,为防止后面再出现该问题,将 filepath 这个进行优化,不采用 sys.path方法,改为如下:

 1     def getValue(self,section,option):
 2         """
 3         @file: string,the name of the config file
 4         @section: string,the name of the section in config file
 5         @option: string,the name of the option in section field
 6         This function will return a int value which the option is specified.
 7         """
 8         try:
 9             configs = ConfigParser()
10             filepath = "../config/" + self.filename + ".ini"
11 #             print (filepath)
12             line = configs.read(filepath)
13             result = configs.getint(section, option)
14             return int(result)
15         except Exception as e:
16             print (e)

 

阅读(1528) 评论(0)