简体   繁体   中英

How to import module from other directory in python

I have a file tree like this:

app
|---src
|    |---vlep/config.py
|
|---tests
     |---conftest.py

from conftest.py I am trying to import vlep.confi as config and I am getting the ModulenotFoundError: No module named 'vlep' . I am using venv and I added absolute paths for app , src and vlep directories to venv/bin/activate , so when I activate the virtualenv I can have these directories in the PYTHONPATH env. I thought that this would do the job, but no...and have no idea why. What am I doing wrong?

You need to set the file path manually to import the modules from another directory. You can assign a directory path to the PYTHONPATH variable and still get your program working.

In Linux, you can use the following command in the terminal to set the path:

export PYTHONPATH='path/to/directory'

In Windows system:

SET PYTHONPATH='path/to/directory'

To see if PYTHONPATH variable holds the path of the new folder, you can use the following command:

echo $PYTHONPATH

Then you can do your imports:

from conftest import vlep.confi as config

You can insert the path to the src folder in sys.path like this:

import os
import sys

sys.path.insert(0, f'{os.path.dirname(os.path.abspath(__file__))}/../src')

from vlep import config

This way the absolute path to your src directory will be first when Python resolves where to import the module from. And it also does not matter what directory you run conftest.py from.

Tks for your time guys. After all there was not wronging to what I was doing to allow the import. The export PYTHONPATH=":/home/user/app/src/vlep" added to the end of venv/bin/activate was enough. The problem was that I was running a script that was changing the value of PYTHONPATH.

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