对于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.pyhelper类有一个方法,该方法返回配置部分中的值。守则如下:
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")如果我不使用绝对路径并运行/home/thisuser/project/folder1/,它将在project/common/中查找配置,并希望它在project/common/中查找,因为/home/thisuser会更改
发布于 2013-02-25 16:13:04
您可以根据模块文件名计算新的绝对路径:
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文件名,以便为您留下指向“当前”目录的绝对路径。
发布于 2013-02-25 16:13:20
我很难理解你真正想要的东西。但是,要以与操作系统无关的方式扩展到主目录的路径,可以使用os.path.expanduser。
self.config = ConfigObj(os.path.expanduser('~/project/common/config.cfg'))https://stackoverflow.com/questions/15071217
复制相似问题