简体   繁体   English

如何从python中的其他目录导入模块

[英]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' .从 conftest.py 我试图import vlep.confi as config ,我得到了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.我正在使用 venv 并将appsrcvlep目录的绝对路径添加到venv/bin/activate ,因此当我激活 virtualenv 时,我可以在 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.您可以为 PYTHONPATH 变量分配一个目录路径,并且仍然可以让您的程序运行。

In Linux, you can use the following command in the terminal to set the path: Linux,可以在终端使用如下命令设置路径:

export PYTHONPATH='path/to/directory'

In Windows system:在Windows系统中:

SET PYTHONPATH='path/to/directory'

To see if PYTHONPATH variable holds the path of the new folder, you can use the following command:要查看 PYTHONPATH 变量是否包含新文件夹的路径,可以使用以下命令:

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:您可以像这样在sys.path中插入src文件夹的路径:

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.这样,当 Python 解析从哪里导入模块时,您的src目录的绝对路径将是第一个。 And it also does not matter what directory you run conftest.py from.从哪个目录运行conftest.py也无关紧要。

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.添加到venv/bin/activate末尾的export PYTHONPATH=":/home/user/app/src/vlep"就足够了。 The problem was that I was running a script that was changing the value of PYTHONPATH.问题是我正在运行一个正在更改 PYTHONPATH 值的脚本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM