2013-02-25 144 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