【问题标题】:How to read config file from module and from main file?如何从模块和主文件中读取配置文件?
【发布时间】:2012-10-02 12:36:55
【问题描述】:

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

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

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

D:\tmp\test>python mainfile.py

D:\tmp\test>

我的目录结构:

测试/ 目录1/ __init__.py imptest.py 静止的/ 配置文件.cfg 主文件.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 的解决方案是更好、更差还是相同?

【问题讨论】:

    标签: python import module python-3.x configparser


    【解决方案1】:

    如果您想要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]

    【讨论】:

    • 谢谢!它正在工作,但我想知道我的解决方案是更好、更差还是和你的一样?
    • 对我来说看起来差不多。我唯一要注意的是os.path.join 负责连接多个路径组件,因此您实际上并不需要os.path.sep
    • 看来你的解决方案更好。我测试了它,它工作得很好,完全符合我的预期。非常感谢您的帮助。为你+1! :-)
    【解决方案2】:

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

    有趣的是,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())
    []
    >>> 
    

    【讨论】:

      猜你喜欢
      • 2014-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-13
      • 1970-01-01
      • 2019-06-22
      • 1970-01-01
      • 2019-01-29
      相关资源
      最近更新 更多