简体   繁体   English

Python 脚本导入失败

[英]Python import failure in script

I have a project structure, like so:我有一个项目结构,如下所示:

 └──     auto/
 │  ├────     __init__.py
 │  └────     __pycache__/
 │  ├────     deploy
 │  ├────     destroy
 │  └────     helpers/
 │  │  ├────     __init__.py
 │  │  ├────     cli.py
 │  │  └────     zip.py
 │  └────     synth
└──     src/
 │  ├────     __init__.py
 │  ├────     main.py
 │  └────     models/
 │  │  ├────     __init__.py
 │  │  ├────     filter.py
 │  │  └────     json_extract_config.py
 │  └────     utils/
 │  │  ├────     __init__.py
 │  │  └────     json_extractor.py

I am trying to call the script synth in the./auto/synth location.我正在尝试在 ./auto/synth 位置调用脚本synth

The synth file is a script with a shebang at the top #!/usr/bin/env python3合成器文件是顶部带有 shebang 的脚本#!/usr/bin/env python3

It imports a function from the./auto/helpers/zip.py file.它从 ./auto/helpers/zip.py 文件中导入 function。

When I run, ./auto/synth from the root folder it throws an error:当我运行时,根文件夹中的./auto/synth会引发错误:

from auto.helpers.zip import zip_folder

ModuleNotFoundError: No module named 'auto'

Although when I run PYTHONPATH="$PWD"./auto/synth the script executes successfully.虽然当我运行PYTHONPATH="$PWD"./auto/synth时脚本成功执行。

Can someone help me understand this behaviour and how to avoid it so that my scripts can be run normally without having to change the PYTHONOPATH?有人可以帮助我理解这种行为以及如何避免它,以便我的脚本可以正常运行而无需更改 PYTHONOPATH 吗?

Thanks in advance.提前致谢。

If you are using python version 3.3+ you do not need to use the __init__.py files anymore, as the namespacing is built into the modules now.如果您使用 python 3.3+ 版,则不再需要使用 __init__.py 文件,因为命名空间现在已内置到模块中。 link --> Is __init__.py not required for packages in Python 3.3+链接 --> Python 3.3+ 中的包不需要 __init__.py

I believe you will have to add the {full path}/src and {full path}/auto directories to the PYTHONPATH to provide python scripts the proper pathing, or you can use the python sys module and use sys.path inside your modules to set your pathing for the module you would like to import link --> https://docs.python.org/3/tutorial/modules.html#the-module-search-path我相信您必须将 {full path}/src 和 {full path}/auto 目录添加到 PYTHONPATH 以提供 python 脚本正确的路径,或者您可以使用 python sys 模块并在模块中使用 sys.path为要导入链接的模块设置路径-> https://docs.python.org/3/tutorial/modules.html#the-module-search-path

import sys
# example path could be "C:/Users/Bob/Desktop/project/auto"
sys.path.append("{full path to your auto directory}/auto")

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

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