簡體   English   中英

Python-從另一個包中的一個包創建類的對象

[英]Python - create object of class from one package in different package

幾天前,我開始使用Python,我認為我有一個非常基本的問題,就是我被困在哪里。 也許我在Python中無法正確執行此操作,因此希望獲得專家的一些建議:

我在一個包庫中有一個config.cfg和一個類測試,如下所示:

的Myproj / LIB /則pkg1 /的config.cfg

[api_config]
url = https://someapi.com/v1/
username=sumitk

的Myproj / LIB /則pkg1 / test.py

class test(object):

    def __init__(self, **kwargs):

        config = ConfigParser.ConfigParser()
        config.read('config.cfg')
        print config.get('api_config', 'username') 
          #just printing here but will be using this as a class variable

    def some other foos()..

現在我想在其他包中的其他模塊中創建測試對象

的Myproj /示例/ useTest.py

from lib.pkg1.test import test

def temp(a, b, c):
    var = test()

def main():
    temp("","","")

if __name__ == '__main__':
    main()

運行useTest.py給我錯誤:

...
print config.get('api_config', 'username')
File "C:\Python27\lib\ConfigParser.py", line 607, in get
     raise NoSectionError(section)
ConfigParser.NoSectionError: No section: 'api_config'

現在,如果我將useTest.py放在同一個程序包中,它將運行得很好:

myProj/lib/pkg1/useTest.py
myProj/lib/pkg1/test.py
myProj/lib/pkg1/config.cfg

我猜想Python中有一些我不了解的非常基本的包訪問概念,或者我在這里做錯了什么?

這里的問題是您有不同的工作目錄,這取決於您的主腳本是哪個模塊。 您可以通過在每個腳本的頂部添加以下幾行來檢查工作目錄:

import os
print os.getcwd()

因為您僅提供'config.cfg'作為文件名,所以它將嘗試在工作目錄中查找該文件。

要解決此問題,請為您的配置文件提供絕對路徑。

您應該可以使用以下方法找出絕對路徑,因為您知道config.cfg和test.py位於同一目錄中:

# inside of test.py
import os
config_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                           'config.cfg')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM