Python 3 中的相对导入不起作用 [英] Relative import in Python 3 is not working

查看:30
本文介绍了Python 3 中的相对导入不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下目录:

mydirectory
├── __init__.py
├── file1.py 
└── file2.py

我在 file1.py 中定义了一个函数 f.

I have a function f defined in file1.py.

如果在 file2.py 中,我会

If, in file2.py, I do

from .file1 import f

我收到以下错误:

系统错误:父模块''未加载,无法执行相对导入

SystemError: Parent module '' not loaded, cannot perform relative import

为什么?以及如何让它发挥作用?

Why? And how to make it work?

推荐答案

由于 file1file2 在同一个目录下,你甚至不需要有一个__init__.py 文件.如果你要扩大规模,那就把它留在那里.

since file1 and file2 are in the same directory, you don't even need to have an __init__.py file. If you're going to be scaling up, then leave it there.

要在同一个目录下的文件中导入一些东西,就这样做

To import something in a file in the same directory, just do like this

from file1 import f

即,您不需要执行相对路径 .file1 因为它们在同一目录中.

i.e., you don't need to do the relative path .file1 because they are in the same directory.

如果将运行整个应用程序的主函数、脚本或其他任何内容都在另一个目录中,那么您必须将所有内容与正在执行的位置相关联.

If your main function, script, or whatever, that will be running the whole application is in another directory, then you will have to make everything relative to wherever that is being executed.

这篇关于Python 3 中的相对导入不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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