简体   繁体   中英

Python - create object of class from one package in different package

I started using Python few days back and I think I have a very basic question where I am stuck. Maybe I am not doing it correctly in Python so wanted some advice from the experts:

I have a config.cfg & a class test in one package lib as follows:

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()..

Now I want to create an object of test in some other module in a different package

myProj/example/useTest.py

from lib.pkg1.test import test

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

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

if __name__ == '__main__':
    main()

Running useTest.py is giving me error:

...
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'

Now if I place thie useTest.py in the same package it runs perfectly fine:

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

I guess there is some very basic package access concept in Python that I am not aware of or is there something I am doing wrong here?

The issue here is that you have a different working directory depending on which module is your main script. You can check the working directory by adding the following lines to the top of each script:

import os
print os.getcwd()

Because you just provide 'config.cfg' as your file name, it will attempt to find that file inside of the working directory.

To fix this, give an absolute path to your config file.

You should be able to figure out the absolute path with the following method since you know that config.cfg and test.py are in the same directory:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM