简体   繁体   English

从 Python 中的不同文件夹导入模块时出错

[英]Error when importing modules from different folders in Python

I have the following:我有以下内容:

my_project/
    hybrik/
        __init__.py
        models/
            __init__.py
            builder.py
    scripts/
        demo.py

And in demo.py:在 demo.py 中:

from hybrik.models import builder

When I tried to run demo.py, an error occured:当我尝试运行 demo.py 时,出现错误:

ModuleNotFoundError: No module named 'hybrik'

I've already had __init__.py , why can't it find the module?我已经有了__init__.py ,为什么找不到模块?

Python will look for modules in locations on the PYTHONPATH . Python 将在PYTHONPATH上的位置查找模块。

Assuming the actual code in those 4 Python files makes sense, you can do the following:假设这 4 个 Python 文件中的实际代码有意义,您可以执行以下操作:

  • on PowerShell:在 PowerShell 上:
$env:pythonpath += ";/path/to/my_project"
  • on Windows command prompt:在 Windows 命令提示符下:
set PYTHONPATH=%PYTHONPATH%;/path/to/my_project
  • on a Linux shell:在 Linux 外壳上:
PYTHONPATH=$PYTHONPATH:/path/to/my_project

Alternatively, you can build a package and install it in the environment of your script.或者,您可以构建一个包并将其安装在脚本环境中。

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

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