Lucas Amos
Lucas Amos

Reputation: 1195

"ImportError: No module named..." when importing my own module

I am trying to import a module and I keep getting an ImportError.

In the PortfolioStatus.py file I have the following code which imports the share_data class from the share_data.py module
from Shares.share_data import share_data

I am getting the following error:

File "/home/lucasamos/FYP/Shares/Communication/PortfolioStatus.py", line 3, in <module>
from Shares.share_data import share_data
ImportError: No module named Shares.share_data

To make things more confusing this works fine on my local machine but I am hosting on PythonAnywhere and this is where I am getting the error

My file hierarchy is show in the image below

File hierarchy

Thanks in advance!

Upvotes: 15

Views: 43046

Answers (4)

Andriy Ivaneyko
Andriy Ivaneyko

Reputation: 22021

Add empty __init__.py on one level with manage.py file.

Such inclusion of __init__.py file indicates to the Python interpreter that the directory should be treated as a Python package.

Upvotes: 5

Lucas Amos
Lucas Amos

Reputation: 1195

OK so I finally worked it out. As indicated by a few of the answers I needed to add my root folder to the system path.

In the end this is what I did:

import sys
sys.path.append("/home/lucasamos/FYP")

Upvotes: 13

Jeff
Jeff

Reputation: 1152

This is likely because your Shares directory is not in your PYTHONPATH.

See this article about using PYTHONPATH: https://users-cs.au.dk/chili/PBI/pythonpath.html

Excerpt:

Often however, you will need to import a module not located in the same directory as the main program. Continuing the example above, assume you're writing a program located in ~/PBI/ which needs to include mymodule.py.

In order for the Python interpreter to find your module, you need to tell it where to look. You can do that by setting the environment variable PYTHONPATH. Depending on the shell program you use (e.g., xterm), this is done in one of two ways.

Bash:

export PYTHONPATH=${PYTHONPATH}:/users/[your username]/PBI/Modules/

Upvotes: 0

CoMartel
CoMartel

Reputation: 3591

you should try this:

import sys
sys.path.append("../Shares/templates")
import share_data

It adds your templates folder to the list of path python is checking for modules.

Upvotes: 11

Related Questions