从同一父目录中的其他文件夹导入模块时出错 [英] Error when importing module from a different folder in the same parent directory

查看:147
本文介绍了从同一父目录中的其他文件夹导入模块时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下python包结构:

I have the following python package structure:

rkstr8/cloud/batch.py
rkstr8/profiling/test.py

我正在尝试将一个名为BatchJobListStatusPoller的类从batch.py​​导入到test.py中,但是当我在test.py中运行此import语句时,却出现了错误:ModuleNotFoundError: No module named 'rkstr8':

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:

from rkstr8.cloud.batch import BatchJobListStatusPoller

rkstr8/文件夹以及cloud/和profiling/子文件夹都具有__init__.py.

The rkstr8/ folder, as well as the cloud/ and profiling/ sub-folders all have an __init__.py.

我在这里做什么错了?

推荐答案

问题是因为Python仅从运行程序python test.py的位置的目录/子目录中导入模块.它还在sys.path变量中搜索模块,该模块包括标准库模块和从pip安装的模块.我可以想到两种方法来解决此问题,一种是更标准的方法,一种是更多非常规的解决方法.

The problem is because Python only imports modules from directories/subdirectories of wherever you run your program python test.py. It also searches for modules in the sys.path variable which includes the standard library ones and any installed from 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.

  1. 第一种方法是直接在aws-sfn-tutorial文件夹中创建一个脚本,该脚本可能称为start_test.py.其唯一目的是在启动时调用test.py脚本,并向下传递任何命令行参数.
    这样,您的test.py脚本就可以正确找到aws-sfn-tutorial文件夹中的所有python模块.

  1. The first way would be to have a script directly in the aws-sfn-tutorial folder maybe called start_test.py. Its sole purpose is to call your test.py script upon starting up and pass any command line arguments down.
    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中的sys.path变量,以添加要导入文件的路径.

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.

  • 您可以指定相对路径../,将其相对于当前路径上移一个文件夹
  • 或者您可以指定文件夹的绝对路径
  • You can either specify a relative path ../ which moves it one folder up relative to the current path
  • Or you can specify the absolute path to the folder

示例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 

这篇关于从同一父目录中的其他文件夹导入模块时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆