2013-02-25 143 views
0

我在使用configobj for 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它看起来为配置在/HO我/ thisuser /项目/文件夹1/,我希望它看起来它在项目/普通/因为/家庭/ thisuser将改变

回答

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文件名以给您提供“当前”目录的绝对路径。

+0

Arg。我正要在我的下一个编辑中提到'__file__' ... – mgilson 2013-02-25 16:13:59

+0

太棒了!这正是我所期待的。 – aj000 2013-02-25 16:51:30

0

我有点难以追随你真正想要的东西。但是,要以操作系统无关的方式扩展到您的主目录的路径,您可以使用os.path.expanduser

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

这也适用,但正在寻找'__file__'。谢谢! – aj000 2013-02-25 16:51:59