gpt4 book ai didi

python导入错误

转载 作者:太空狗 更新时间:2023-10-30 02:35:19 25 4
gpt4 key购买 nike

我的导入有什么问题?

应用文件夹结构:

我的应用/

  • models/models.py 包含 SpotModel()
  • tests/tests.py 包含 TestSpotModel(unittest.TestCase)。 tests.py imports from myapp.models.models import * 这就像一个魅力
  • scripts/import.py 包含 from myapp.models.models import *

问题是 import.py 在执行时会导致错误:

ImportError: No module named myapp.models.models

但是 tests.py 运行。

我有 __init__.py 文件在 myapp/__init__.py, myapp/models/__init__.py, myapp/tests/__init__.py 并且如前所述,使用 nosetests 运行单元测试按预期工作。

最佳答案

它是 __init__.py 而不是 init.py。确保层次结构中的每个目录都包含它以便能够导入。

编辑:我设法重现了它。这是目录结构:

cesar@cesar-laptop:/tmp/asdasd$ tree.`-- myapp    |-- __init__.py    |-- models    |   |-- __init__.py    |   `-- models.py    |-- scripts    |   |-- data.py    |   `-- __init__.py    `-- tests        |-- __init__.py        `-- tests.py

I put the following code at the very beginning of the data.py to narrow down the problem:

import sys
import pprint

pprint.pprint(sys.path)

from myapp.models.models import *

按照 OP 指示的方式运行 data.py 会产生 ImportError:

cesar@cesar-laptop:/tmp/asdasd$ python myapp/scripts/data.py['/tmp/asdasd/myapp/scripts', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/python2.6/lib-tk', -- Skipped --'/usr/local/lib/python2.6/dist-packages']Traceback (most recent call last):  File "myapp/scripts/data.py", line 6, in     from myapp.models.models import *ImportError: No module named myapp.models.models

但这种方式很有魅力:

cesar@cesar-laptop:/tmp/asdasd$ python -m myapp.scripts.data['', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/python2.6/lib-tk', -- Skipped --'/usr/local/lib/python2.6/dist-packages']

注意 sys.path 第一个条目的区别。

关于python导入错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3537850/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com