【问题标题】:Import error in python after all solutions tried尝试所有解决方案后python中的导入错误
【发布时间】:2021-08-17 18:15:49
【问题描述】:

我感觉被 Python 打败了,以至于我不知道还能尝试什么。我正在运行 Python 3.9,但我一生都无法让导入正常工作。这是我的目录结构:

hello-world-proj
|
|.. core
   |
   |..
       __init__.py
       hello_world_main.py
|
|.. test
   |
   |..
       __init__.py
       test_hello_world_main.py

hello_world_main.py

def hello_world_main():
   return "myString"

if __name__ == "__main__":
   print(hello_world_main()) # call hello_world_main()

test_hello_world_main.py

import unittest
import os
from core import hello_world_main

class HelloWorldTest(unittest.TestCase):
   self.assertEquals(hello_world_main(), "myString")

if __name__ == '__main__':
    unittest.main(exit=False)

当我运行 python test_hello_world_main.py 时,我遇到了错误:

ImportError: cannot import name hello_world_main

我已经做了export PYTHONPATH=$PYTHONPATH:/path/to/hello-world-proj

我被打败了,不知道现在该怎么办。为什么会这样?

【问题讨论】:

  • core 模块中的__init__.py 文件是什么样的?
  • @aminrd 他们都是空文件

标签: python terminal


【解决方案1】:

解决方案一:

已经设置了export PYTHONPATH=$PYTHONPATH:/path/to/hello-world-proj,在core 中编辑__init__.py,例如:

from .hello_world_main import hello_world_main

解决方案二:

从同一目录运行您的测试并编辑测试文件,如下所示:

import unittest
import os
from core.hello_world_main import hello_world_main

class HelloWorldTest(unittest.TestCase):
   self.assertEquals(hello_world_main(), "myString")

if __name__ == '__main__':
    unittest.main(exit=False)

然后在hello-world-proj 中运行你的命令:

python test/test_hello_world_main.py

【讨论】:

  • 这很奇怪。仅当我将其包含在 HelloWorldTest 类中时它才起作用。如果我将其删除并像常规脚本一样将其放在外面,它会起作用。为什么会这样?所以如果b.pyfrom core.hello_world_main import hello_world_main print(hello_world_main()) 它实际上是有效的,但是如果你在测试中使用它,它就不起作用:class HelloWorldTest(unittest.TestCase): self.assertEquals(hello_world_main(), "myString")
【解决方案2】:

如果您只想要 hello_world_main.py 中的特定函数,您的导入语句应该是 from core.hello_world_main import hello_world_main,如果您想要文件中的所有内容,请尝试 from core.hello_world_main import *

【讨论】:

    【解决方案3】:

    TLDR;

    1. 添加 setup.py
    2. 使用以下命令安装您的软件包:pip install -e .

    为了避免摆弄 import 参数,我会在您的顶级目录 (hello-world-proj) 中创建一个 setup.py(您可能已经/需要一个)。

    setup.py

    from setuptools import setup, find_packages
    
    setup(name="hello-world-proj", packages=find_packages())
    

    在您的项目根目录中,然后您 pip install(最好在您的 virtual environment 中)您的项目,并带有指向您的项目位置的符号链接:

    pip install -e .
    

    请注意,您不必在每次更改文件后都执行此操作 - 只需一次。阅读更多this answer

    之后你可以在你的测试文件中使用你当前的from core import hello_world_main

    import unittest
    from core import hello_world_main
    
    class HelloWorldTest(unittest.TestCase):
    
        def test_hello_world(self):
            self.assertEqual(hello_world_main.hello_world_main(), "myString")
    
    if __name__ == '__main__':
        unittest.main(exit=False)
    

    【讨论】:

      猜你喜欢
      • 2023-03-05
      • 2019-02-27
      • 1970-01-01
      • 2015-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多