【问题标题】:Jupyter ImportError: cannot import nameJupyter ImportError:无法导入名称
【发布时间】:2019-09-18 07:53:28
【问题描述】:

我的项目结构如下:

path_to_dir/
│
├── a_notebook.ipynb
└── testCases_v2.py

在 .py 文件中我定义了几个函数。

我正在尝试像这样将它们导入笔记本中:

from testCases_v2 import layer_sizes_test_case

但是,我得到:

ImportError: cannot import name 'layer_sizes_test_case' from 'testCases_v2' (/path_to_dir/testCases_v2.py)

我什至尝试将目录添加到系统路径:

import os
import sys
module_path = os.path.abspath(os.path.join('path_to_dir'))
if module_path not in sys.path:
   sys.path.append(module_path)

但问题依然存在。

如何解决? (而且,是的,我检查了我正在导入的函数的名称是否拼写正确)

【问题讨论】:

  • 你能在那个文件夹中添加一个 empy __init__.py 文件并尝试一下吗?
  • 嗨@Nick,你能找到解决方案吗,我遇到了类似的问题,不胜感激

标签: python-3.x jupyter-notebook


【解决方案1】:

假设你有这个:

path_to_dir/
│
├── a_notebook.ipynb
└── tests
       |
       └── testCases_v2.py

在 testCases_v2 中你有一个同名的类。

  1. 您必须手动导入您希望 Jupyter 使用的模块 sys.path 中的帐户在这种情况下,模块是“测试”,路径 你必须包括的是'path_to_dir'

      import sys  
      sys.path.insert(0, 'path/to/dir')
    
  2. 在你的py文件所在的模块中,添加一个空的__init__.py

     path_to_dir/
     │
     ├── a_notebook.ipynb
     └── tests
         |
         ├──testCases_v2.py
         └── __init__.py
    

您现在应该可以通过以下方式导入它:

from tests.testCases_v2 import testCases_v2 

python doc about modules 可能会派上用场

【讨论】:

  • 它不起作用
猜你喜欢
  • 2021-04-25
  • 2017-10-09
  • 2019-03-23
  • 2021-06-13
  • 1970-01-01
  • 2021-08-05
  • 1970-01-01
  • 2016-03-31
  • 2014-10-10
相关资源
最近更新 更多