Renan C. Araujo
Renan C. Araujo

Reputation: 902

Error when trying to import script in root directory

I have the following directory structure:

├── __init__.py
├── http
│   ├── __init__.py
│   ├── web.py
└── test
    ├── __init__.py
    ├── app.py

Inside the app.py file:

from http import web

When I try to run (in the root dir):

 python test/app.py 

I'm getting the following error:

ImportError: no module named http

I know that I could run using:

python -m test.app

However, there is another way?

Upvotes: 0

Views: 250

Answers (1)

larsks
larsks

Reputation: 312370

When you run python path/to/script.py, python adds the directory containing script.py to the module search path, but doesn't magically add anything else. So when you run python test/app.py, and app.py tries to import http, it's not found because the http module isn't anywhere in the search path. An easy way of solving this would be:

PYTHONPATH=$PWD python test/app.py

This would add your current directory to the module search path. Assuming that you current directory is the one that contains the http module, this would allow app.py to sucessfully import http.

Upvotes: 1

Related Questions