[英]ImportError: No module named modules.TestModule
我已经在这个问题上困扰了很长时间,我的项目结构是这样的,
import web
import sys
sys.path.append("...")
import modules.TestModule as TM
urls = (
'/testmethod(.*)', 'TestMethod'
)
app = web.application(urls, globals())
class TestMethod(web.storage):
def GET(self, r):
return TM.get_func(web.input().string)
if __name__ == "__main__":
app.run()
当我执行TestService.py时,它说“ ImportError:没有名为modules.TestModule Python的模块”
这是用来测试module
的样本。
您的程序的切入点是什么? 通常,程序的入口点将位于项目的根目录。 由于它位于根目录下,因此根目录内的所有模块都是可导入的。 但是在您的情况下,入口点本身是根级别内部的级别。
最好的方法应该是在根目录下有一个加载器文件(main.py),其余文件可以放在包中。 另一种不推荐的方法是在导入任何软件包之前在sys.path中附加根目录路径。
在导入软件包之前,请添加以下代码。
import os, sys
currDir = os.path.dirname(os.path.realpath(__file__))
rootDir = os.path.abspath(os.path.join(currDir, '..'))
if rootDir not in sys.path: # add parent dir to paths
sys.path.append(rootDir)
我已经修改了yut testscript.py代码,如下所示。 请尝试一下。
import web
import sys
import os, sys
currDir = os.path.dirname(os.path.realpath(__file__))
rootDir = os.path.abspath(os.path.join(currDir, '..'))
if rootDir not in sys.path: # add parent dir to paths
sys.path.append(rootDir)
import modules.TestModule as TM
urls = (
'/testmethod(.*)', 'TestMethod'
)
app = web.application(urls, globals())
class TestMethod(web.storage):
def GET(self, r):
return TM.get_func(web.input().string)
if __name__ == "__main__":
app.run()
如果目录“ DiginQ”在您的python sys.path上,我相信您的import语句应该可以正常工作。
有很多方法可以在python路径上获取目录“ DiginQ”。
也许最简单(但不是最好)是在导入模块之前添加如下语句:
import sys
sys.path.extend([r'C:\Python27\DiginQ'])
根据您的帖子,看起来路径是C:\\ Python27 \\ DiginQ,但是如果这样做不正确,请使用正确的路径。
如果您用谷歌搜索如何设置python路径,您会发现很多匹配项。 最重要的是,您的路径必须在目录上方包含要导入的软件包的目录。 就您而言,这就是DiginQ。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.