ConfigObj 和绝对路径

0 投票
2 回答
725 浏览
提问于 2025-04-17 17:03

我在使用Python的configobj时遇到了一些路径问题。我想知道有没有办法在我的辅助文件中不使用绝对路径。比如,我想用这样的方式:

self.config = ConfigObj('/home/thisuser/project/common/config.cfg')

而不是:

self.config = ConfigObj(smartpath+'/project/common/config.cfg')

背景: 我把配置文件放在一个公共目录里,和一个辅助类以及一个工具类放在一起:

common/config.cfg
common/helper.py
common/utility.py

这个辅助类有一个方法,可以返回配置文件中某个部分的值。代码是这样的:

from configobj import ConfigObj

class myHelper:

    def __init__(self):
        self.config = ConfigObj('/home/thisuser/project/common/config.cfg')

    def send_minion(self, race, weapon):
        minion = self.config[race][weapon]
        return minion

工具文件导入了辅助文件,而这个工具文件被项目中不同文件夹里的多个类调用:

from common import myHelper

class myUtility:

    def __init__(self):
        self.minion = myHelper.myHelper()

    def attack_with_minion(self, race, weapon)
        my_minion = self.minion.send_minion(race, weapon)
        #... some common code used by all
        my_minion.login()

以下文件导入了工具文件并调用了这个方法:

/home/thisuser/project/folder1/forestCastle.py
/home/thisuser/project/folder2/secondLevel/sandCastle.py
/home/thisuser/project/folder3/somewhere/waterCastle.py

self.common.attack_with_minion("ogre", "club")

如果我不使用绝对路径,运行forestCastle.py时,它会在/home/thisuser/project/folder1/中寻找配置文件,而我希望它在project/common/中寻找,因为/home/thisuser这个路径会改变。

2 个回答

0

我有点搞不清楚你到底想要什么。不过,如果你想在不同操作系统上都能找到你的家目录,可以使用 os.path.expanduser 这个方法:

self.config = ConfigObj(os.path.expanduser('~/project/common/config.cfg'))
0

你可以根据模块的文件名来计算一个新的绝对路径:

import os.path
from configobj import ConfigObj

BASE = os.path.dirname(os.path.abspath(__file__))


class myHelper:

    def __init__(self):
        self.config = ConfigObj(os.path.join(BASE, 'config.cfg'))

__file__ 是当前模块的文件名,对于 helper.py 来说,它的值可能是 /home/thisuser/project/common/helper.py;而 os.path.abspath() 确保这个路径是绝对路径,接着 os.path.dirname 会去掉 /helper.py 这个文件名,最终给你留下一个指向“当前”目录的绝对路径。

撰写回答