38

我有以下源代码结构

/testapp/
/testapp/__init__.py
/testapp/testmsg.py
/testapp/sub/
/testapp/sub/__init__.py
/testapp/sub/testprinter.py

其中testmsg定义了以下常量:

MSG = "Test message"

sub/testprinter.py

import testmsg

print("The message is: {0}".format(testmsg.MSG))

但我越来越ImportError: No module named testmsg

它不应该从包结构开始工作吗?我真的不想在每个子模块中扩展 sys.path ,我什至不想使用相对导入。

我在这里做错了什么?

4

5 回答 5

27

这完全取决于您运行的脚本。该脚本的路径将自动添加到 python 的搜索路径中。

使其成为以下结构:

TestApp/
TestApp/README
TestApp/LICENSE
TestApp/setup.py
TestApp/run_test.py
TestApp/testapp/__init__.py
TestApp/testapp/testmsg.py
TestApp/testapp/sub/
TestApp/testapp/sub/__init__.py
TestApp/testapp/sub/testprinter.py

然后TestApp/run_test.py 运行:

from testapp.sub.testprinter import functest ; functest()

然后TestApp/testapp/sub/testprinter.py可以这样做:

from testapp.testmsg import MSG
print("The message is: {0}".format(testmsg.MSG))

这里有更多好的提示;

于 2012-07-09T10:51:08.577 回答
11

使用如下的相对导入

from .. import testmsg
于 2012-07-09T10:47:33.337 回答
10

这个问题有答案——动态导入:

如何在父目录中导入python文件

import sys
sys.path.append(path_to_parent)
import parent.file1

这是我用来导入任何东西的东西。当然,您仍然必须将此脚本复制到本地目录,导入它以及use您想要的路径。

import sys
import os

# a function that can be used to import a python module from anywhere - even parent directories
def use(path):
    scriptDirectory = os.path.dirname(sys.argv[0])  # this is necessary to allow drag and drop (over the script) to work
    importPath = os.path.dirname(path)
    importModule = os.path.basename(path)
    sys.path.append(scriptDirectory+"\\"+importPath)        # Effing mess you have to go through to get python to import from a parent directory

    module = __import__(importModule)
    for attr in dir(module):
        if not attr.startswith('_'):
            __builtins__[attr] = getattr(module, attr)
于 2012-10-13T03:15:25.187 回答
10

对于仍然有同样问题的人。这就是我解决我的方法:

import unittest 
import sys
import os

sys.path.append(os.getcwd() + '/..')

from my_module.calc import *
于 2019-10-25T06:16:59.993 回答
0

试试这个:


import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(__file__)))

from my_module import *

于 2021-06-11T10:19:30.637 回答