User avatar
faramon
Posts: 123
Joined: Sat Jun 11, 2016 8:36 am
Location: Croatia

Cannot import py with __init__.py

Tue Sep 20, 2016 7:09 am

Hi,

I read about having __init__.py files because they are required to make Python treat the directories as containing packages.

I have my scripts in directory /home/pi/myPiConfig/ and that scripts are:
__init__.py - empty script
mypi_settings.py

Then I have another child directory /home/pi/myPiConfig/DHT11 with:
__init__.py - empty script
dht11_check.py

My problem is that if I open file dht11_check.py in python ide with code:
#!usr/bin/python
import mypi_settings as mysettings

and I get error:
ImportError: No module named mypi_settings

why? I have removed all pyc files and recompile with no success.

What have i missed? Have can I inport py script from parent directory?

Thanx,
Faramon

scotty101
Posts: 3958
Joined: Fri Jun 08, 2012 6:03 pm

Re: Cannot import py with __init__.py

Tue Sep 20, 2016 8:26 am

Your import statement is wrong.

Code: Select all

from myPiConfig import mypi_settings as mysettings
See http://stackoverflow.com/questions/1260 ... bdirectory
Electronic and Computer Engineer
Pi Interests: Home Automation, IOT, Python and Tkinter

User avatar
faramon
Posts: 123
Joined: Sat Jun 11, 2016 8:36 am
Location: Croatia

Re: Cannot import py with __init__.py

Tue Sep 20, 2016 8:44 am

scotty101 wrote:from myPiConfig import mypi_settings as mysettings
I do import your way and same error: No module named myPiConfig?!?! I read somewhere that pyc files must be deleted and i have deleted those files. But same error...

scotty101
Posts: 3958
Joined: Fri Jun 08, 2012 6:03 pm

Re: Cannot import py with __init__.py

Tue Sep 20, 2016 12:30 pm

Then you need to add the folder to your path.

Code: Select all

sys.path.append('/path/to/folder/to/import/from')
Problem is that your folder structure is this

Code: Select all

/home
    /pi
        myPiConfig
			__init__.py
			mypi_settings.py
			DHT11
				__init__.py
				dht11_check.py
Python's path when you run dht11_check.py will be the DHT11 folder which doesn't contain the mypi_settings.py file. You can import directly from child folders but since it is a parent folder, the best way seems to be to add that folder to your python path.

An even better solution would be to re-architect your project so that the top level python script is importing the dependencies from the child folders rather than having to look to the parent.
Electronic and Computer Engineer
Pi Interests: Home Automation, IOT, Python and Tkinter

User avatar
faramon
Posts: 123
Joined: Sat Jun 11, 2016 8:36 am
Location: Croatia

Re: Cannot import py with __init__.py

Tue Sep 20, 2016 1:19 pm

Thanx,

I will remove the scripts to parent folder, it is not problem.

Thanx,
Faramon

Return to “Python”