简体   繁体   中英

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?

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 .

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