[英]Error when importing module from a different folder in the same parent directory
I have the following python package structure:我有以下python包结构:
rkstr8/cloud/batch.py
rkstr8/profiling/test.py
I'm trying to import a class called BatchJobListStatusPoller
from batch.py into test.py, but it gives me the error: ModuleNotFoundError: No module named 'rkstr8'
when I run this import statement in test.py:我正在尝试将一个名为
BatchJobListStatusPoller
的类从 batch.py 导入到 test.py 中,但是当我在 test.py 中运行此导入语句时,它给了我错误: ModuleNotFoundError: No module named 'rkstr8'
:
from rkstr8.cloud.batch import BatchJobListStatusPoller
The rkstr8/ folder, as well as the cloud/ and profiling/ sub-folders all have an __init__.py
. rkstr8/ 文件夹,以及 cloud/ 和 profiling/ 子文件夹都有一个
__init__.py
。
What am I doing wrong here?我在这里做错了什么?
The problem is because Python only imports modules from directories/subdirectories of wherever you run your program python test.py
.问题是因为 Python 只从你运行程序
python test.py
目录/子目录中导入模块。 It also searches for modules in the sys.path
variable which includes the standard library ones and any installed from pip.它还在
sys.path
变量中搜索模块,其中包括标准库和从 pip 安装的任何模块。 I can think of two ways to solve this problem, one is the more standard way and one is more of an unorthodox workaround.我可以想到两种方法来解决这个问题,一种是更标准的方法,一种更像是一种非正统的解决方法。
The first way would be to have a script directly in the aws-sfn-tutorial
folder maybe called start_test.py
.第一种方法是直接在
aws-sfn-tutorial
文件夹中aws-sfn-tutorial
一个脚本,可能称为start_test.py
。 Its sole purpose is to call your test.py
script upon starting up and pass any command line arguments down.它的唯一目的是在启动时调用
test.py
脚本并向下传递任何命令行参数。
This will allow your test.py
script to then be able to correctly find all the python modules inside the aws-sfn-tutorial
folder.这将使您的
test.py
脚本能够正确地找到aws-sfn-tutorial
文件夹中的所有 python 模块。
The second way would be to modify the sys.path
variable in test.py
to add in the path to the file you want to import.第二种方法是修改
test.py
的sys.path
变量以添加要导入的文件的路径。
../
which moves it one folder up relative to the current path../
将其相对于当前路径向上移动一个文件夹Example of 2:示例 2:
import sys
sys.path.append('../') # Or use the absolute path here instead
# After adding to sys.path import your module
from cloud.batch import BatchJobListStatusPoller
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.