加载和读取配置文件时出现问题。当我运行imptest.py
文件时,Python读取configfile.cfg
,得到以下输出:
D:\tmp\test\dir1>python imptest.py
Section1
Section2
Section3
但是当我运行mainfile.py
文件时,什么都没有发生,而且Python似乎没有读取configfile.cfg
文件:
我的目录结构:
test/ dir1/ __init__.py imptest.py static/ configfile.cfg mainfile.py
mainfile.py
文件的源:
from dir1.imptest import run
if __name__ == '__main__':
run()
imptest.py
文件的源:
import configparser
def run():
config = configparser.ConfigParser()
config.read('../static/configfile.cfg', encoding='utf8')
for sections in config.sections():
print (sections)
if __name__ == '__main__':
run()
configfile.cfg
文件的源:
[Section1]
Foo = bar
Port = 8081
[Section2]
Bar = foo
Port = 8080
[Section3]
Test = 123
Port = 80
已编辑
到目前为止,我的解决方案(绝对路径)是:
cwd = os.path.realpath(os.path.dirname(__file__) + os.path.sep + '..')
config.read(os.path.join(cwd,'static' + os.path.sep + 'configfile.cfg'), encoding='utf8')
它是更好的,更差的还是与@Yavar的解决方案相同?在
如果需要
imptest.py
的相对路径,请使用__file__
:另外,请参阅此问题的答案: Difference between __file__ and sys.argv[0]
它找不到配置文件,因为从主文件版本调用时没有使用正确的路径。在
有趣的是,configparser会自动忽略。看看这个:
相关问题 更多 >
编程相关推荐