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

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

问题描述

我有以下目录:

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

我有一个定义的函数f file1.py。

I have a function f defined in file1.py.

如果,在file2.py中,我

If, in file2.py, I do

from .file1 import f

我收到以下错误:


SystemError:父模块''未加载,无法执行相对
导入

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

为什么?以及如何使它工作?

Why? And how to make it work?

推荐答案

因为 file1 file2 位于同一目录中,您甚至不需要 __ 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

来自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天全站免登陆