简体   繁体   English

在 Python3.9 中导出和导入定义的函数

[英]Export and Import a defined function in Python3.9

I have been attempting to define a python function in one script (lets call it script1.py) like so:我一直在尝试在一个脚本中定义一个 python 函数(我们称之为 script1.py),如下所示:

def fn1(): 
 print("Hello")

and then to import it into a separate python file in the same directory (lets call it script2.py) like this:然后将其导入到同一目录中的单独 python 文件中(我们称之为 script2.py),如下所示:

from script1 import fn1 or import script1 from script1 import fn1import script1

I've found lots of posts/answers supporting this process, but I continue to receive the error message that there is "No module named 'script1'".我找到了很多支持此过程的帖子/答案,但我继续收到错误消息“没有名为‘script1’的模块”。 Most of the posts I've seen are from 3+ years ago, so perhaps the newer versions of python have terminated this option.我看到的大多数帖子都是 3 年前的,所以也许较新版本的 python 已经终止了这个选项。

I appreciate any solutions!我感谢任何解决方案!

If your two files are in the same folder, you can try adding a blank __init__.py file to your folder and using a relative import:如果您的两个文件在同一个文件夹中,您可以尝试将一个空白的 __init__.py 文件添加到您的文件夹中并使用相对导入:

from .script1 import fn1

Adding the '.'添加“.” before the module name ensures that your script is looking in the current directory.在模块名称之前确保您的脚本正在当前目录中查找。

To specify the parent directory, try: from {folder_name}.script1 import fn1 where folder_name is parent directory要指定父目录,请尝试: from {folder_name}.script1 import fn1 where folder_name 是父目录

You can read more about relative imports in Python 3 documentation .您可以在Python 3 文档中阅读有关相对导入的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM