从父级目录中的另一个文件夹中的模块导入函数
我一直在尝试解决这个问题几个小时。 这是我的文件夹结构。
/parent_folder
main.py
module1/
script1.py
module2/
script2.py
script2.py
只有此内部:
def subtract_numbers(x, y):
return x - y
我希望Script1.py能够调用此功能。 我有:
from ..module2.script2 import subtract_numbers
result_subtraction = subtract_numbers(5, 5)
print(result_subtraction)
我得到Importerror:未知的父母软件包
的尝试相对导入,
我在scrip1.py
中的导入行中尝试了许多不同的排列,但是我遇到了相同的错误。我还必须注意,我有两个文件夹中的__ INT __。py
文件。
我该如何确切地调用script2.py
中的函数?
I have been trying unsuccessfully to solve this for hours now.
This is my folder structure.
/parent_folder
main.py
module1/
script1.py
module2/
script2.py
script2.py
has only this inside:
def subtract_numbers(x, y):
return x - y
I want script1.py to be able to call this function.
I have:
from ..module2.script2 import subtract_numbers
result_subtraction = subtract_numbers(5, 5)
print(result_subtraction)
I get ImportError: attempted relative import with no known parent package
I have tried many different permutations in the import line in scrip1.py
but i get the same error. I also have to note that i have __init__.py
files in the two folders.
How exactly can i call the function in script2.py
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
相对导入不能比
python
呼叫的级别更高。因此,您的问题是您直接从module1
目录调用script1.py
。我猜是这样的事情:因此,您需要从可以实际看到
script.py2.py
的级别中调用script1.py
。首先,将您的相对导入更改为
script1.py
中的绝对导入:然后,移至
module1
的父级目录那里的脚本(请注意提示中的位置):Relative imports cannot go back to a higher level than the one from which the
python
call was originated. So, your problem here is that you are invokingscript1.py
directly from themodule1
directory. I guess something like this:So you will need to make your call to
script1.py
from a level where you can actually seescript2.py
.First, change your relative import to absolute import in
script1.py
:Then, move back to the parent directory of
module1
and run the module as a script from there (note the location in the prompt):这对我有用。
我将父目录的目录(
/parent_folder
)导出到pythonpath
。然后,内部文件
module1/script1.py
,我更改了这一行:现在我可以调用在
Module2/ script2.py
带有python script1.py
,它将起作用。我还必须注意,我到处都有
__ INT __。
This is what worked for me.
I exported the directory of the parent directory (
/parent_folder
) to thePYTHONPATH
.Then, inside file
module1/script1.py
, i had this line changed:Now i can call the script
script1.py
that calls the function declared inmodule2/script2.py
withpython script1.py
and it will work.I also have to note that i have
__init__.py
files everywhere (in the parent directory and both subfolders), but i am now sure if this is vital.