Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
913 views
in Technique[技术] by (71.8m points)

import - Python importing a module from a parallel directory

How would I organize my python imports so that I can have a directory like this.

project
|      
|      __init__.py
|     
src
|   
|    __init__.py
|    classes.py
|
test
    
     __init__.py
     tests.py

And then inside /project/test/tests.py be able to import classes.py

I've got code looking like this in tests.py

from .. src.classes import(
    scheduler
    db
)

And am getting errors of

SystemError: Parent module '' not loaded, cannot perform relative import

Anyone know what to do?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Python adds the folder containing the script you launch to the PYTHONPATH, so if you run

python test/tests.py

Only the folder test is added to the path (not the base dir that you're executing the command in).

Instead run your tests like so:

python -m test.tests

This will add the base dir to the python path, and then classes will be accessible via a non-relative import:

from src.classes import etc

If you really want to use the relative import style, then your 3 dirs need to be added to a package directory

package
* __init__.py
* project
* src
* test

And you execute it from above the package dir with

python -m package.test.tests

See also:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...