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

2018-11-09 02:40:55来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

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

 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)

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:第十五天-面向对象01

下一篇:CentOS 7下安装Python3.6