“无模块”尽管有相同的目录,但我自己的函数出错

发布于 2025-01-10 02:41:21 字数 424 浏览 0 评论 0原文

我正在 Jupyter 笔记本中编写脚本文件 &我需要调用一个函数。我创建了另一个名为 myfunctions.py 的文件,并在那里定义了名为 Give_ans() 的函数。稍后我还会在这里提供更多功能。但是当我使用以下命令时,我在主脚本文件中收到错误消息

from myfunctions import give_ans

No module named 'myfunctions'。我使用 pwd 查看它们的路径,它与“C:\Users\my name\OneDrive\my_code”完全相同。所以我不知道这个错误的原因是什么。请指教。我一直是一名 Matlab 编码员,这是我在这里的第一次尝试。

更新:我发现了问题&修好了。我在下面的回答中给出了解决方案。

I am writing a script file in the Jupyter notebook & I need to call a function. I created another file called myfunctions.py and defined my function called give_ans() there. I will have many more functions here later. But I get an error in the main script file when I use the following command

from myfunctions import give_ans

The error is No module named 'myfunctions'. I use pwd to see their path and it is exactly the same which is 'C:\Users\my name\OneDrive\my_code'. So I don't know what is the cause of this error. Please advise. I have always been a Matlab coder and this is my first attempt here.

Update: I found the problem & fixed it. I gave the solution in my answer below.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

橙幽之幻 2025-01-17 02:41:21

我发现出了什么问题。我的两个 Jupyter 文件都是 .ipynb 扩展名,而我打算导入的 myfunctions.ipynb 脚本应该是 .py 形式。为此,我进入命令窗口(在我的例子中是 Anaconda),进入问题中提到的同一目录,然后执行以下操作。

pip install ipynb-py-convert
jupyter nbconvert --to python myfunctions.ipynb

这生成了一个 .py 文件,然后使用我在问题中所写的导入语句时没有错误。

编辑:任何阅读此答案的人也请务必阅读下面的评论。

I found out what was going wrong. Both of my Jupyter files are of the .ipynb extension whereas the myfunctions.ipynb script that I intend to import should be in .py form. To do so, I went to the command window (Anaconda one in my case), went to the same directory as mentioned in the question, and did the following.

pip install ipynb-py-convert
jupyter nbconvert --to python myfunctions.ipynb

This produced a .py file and then there was no error upon using the import statements as I wrote in the question.

Edit: Anyone reading this answer please also make sure to read the comments below.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文