简体   繁体   English

Jupyter Notebook Pycharm 2019 IDE 中的 Python 导入错误

[英]Python import error in Jupyter Notebook Pycharm 2019 IDE

I recently installed PyCharm 2019 professional edition in Windows 10. I created a new Project 'Sample' and two files 'file1.py' and 'file2.ipynb'.我最近在 Windows 10 中安装了 PyCharm 2019 专业版。我创建了一个新项目“示例”和两个文件“file1.py”和“file2.ipynb”。 I have installed jupyter notebook from the chosen python interpreter.我已经从所选的 python 解释器安装了 jupyter notebook。

  1. class Foo is defined in file1.py类 Foo 在 file1.py 中定义
  2. I then import file1.py into file2.ipynb to use Foo然后我将 file1.py 导入 file2.ipynb 以使用 Foo

Here, I encounter a strange error.在这里,我遇到了一个奇怪的错误。 2019 professional edition has local notebook server installed in it. 2019 专业版已安装本地笔记本服务器。

from file1 import Foo

I ran the above code sample in a cell both in editor inside PyCharm IDE as well as in browser, after turning on the jupyter server on localhost.在本地主机上打开 jupyter 服务器后,我在 PyCharm IDE 内的编辑器和浏览器中的单元格中运行了上述代码示例。

For some reason, the code sample throws out import error problem in IDE but runs smoothly in browser.出于某种原因,代码示例在IDE中抛出了导入错误问题,但在浏览器中运行流畅。 I tried looking if there are any issues with project path but couldn't figure out the reason yet.我尝试查看项目路径是否存在任何问题,但仍无法找出原因。 Anyone encountered this before ?以前有人遇到过这个吗?

Here is the screenshot of Import Error:这是导入错误的屏幕截图: 在此处输入图片说明

os.getcwd() helped me understand the problem. os.getcwd() 帮助我理解了这个问题。 The jupyter notebook editor is running under Main directory 'Sample'. jupyter 笔记本编辑器在主目录“示例”下运行。 Whereas my files are in 'Sample/Resource/file1.py', 'Sample/Resource/file2.ipynb' .而我的文件在 'Sample/Resource/file1.py', 'Sample/Resource/file2.ipynb' 中。

Now If I import using the following commands in file2.ipynb file, it worked:现在,如果我在 file2.ipynb 文件中使用以下命令导入,它会起作用:

import os
print(os.getcwd())
#%%
from Source import file1
print(file1.Foo())

Thank you very much for the help @Vishal @IonicSolutions非常感谢@Vishal @IonicSolutions 的帮助

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

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