如何从模块和主文件中读取配置文件?

2024-09-30 01:28:35 发布

您现在位置:Python中文网/ 问答频道 /正文

加载和读取配置文件时出现问题。当我运行imptest.py文件时,Python读取configfile.cfg,得到以下输出:

D:\tmp\test\dir1>python imptest.py
Section1
Section2
Section3

但是当我运行mainfile.py文件时,什么都没有发生,而且Python似乎没有读取configfile.cfg文件:

^{pr2}$

我的目录结构:

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的解决方案相同?在


Tags: 文件pathrunpytestconfigosport
2条回答

如果需要imptest.py的相对路径,请使用__file__

mydir = os.path.dirname(os.path.abspath(__file__))
new_path = os.path.join(mydir, '..', rest_of_the_path)

另外,请参阅此问题的答案: Difference between __file__ and sys.argv[0]

它找不到配置文件,因为从主文件版本调用时没有使用正确的路径。在

有趣的是,configparser会自动忽略。看看这个:

Python 3.2.3 (default, Sep 10 2012, 18:14:40) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import configparser
>>> 
>>> config = configparser.ConfigParser()
>>> config.read('doesnotexist.cfg')
[]
>>> print(config.sections())
[]
>>> 

相关问题 更多 >

    热门问题