如何调试ImportError(使用系统路径正确)

2024-10-03 06:30:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我通过CherryPy提供django页面。当CherryPy在前台启动时,一切都正常。当我把切里皮和

Daemonizer(cherrypy.engine).subscribe()

我收到了一封信。 sys.path在这两种情况下(daemonized和non-daemonized)是完全相同的。除了sys.path影响python导入之外,还有什么可以调试呢?在

附加信息

回溯:

^{pr2}$
  • 要导入的文件:/home/fbx/code/plinth/plinth/modules/first_boot/middleware.py
  • 相关的系统路径条目(当ImportError发生时也出现):'/home/fbx/code/plinth'
  • ImportError出现在https://github.com/django/django/blob/master/django/utils/importlib.py中的djangosimport_module函数中。在
  • import_module的参数name"plinth.modules.first_boot.middleware"
  • django中间件的类设置是'plinth.modules.first_boot.middleware.FirstBootMiddleware'

还有一个注意事项:
我用python -m plinth在目录/home/fbx/code/plinth运行守护服务器。
当我用/usr/bin/python /home/fbx/code/plinth/plinth/__main__.py启动守护服务器时,一切正常!在本例中,sys.path有一个附加条目:/home/fbx/code/plinth/plinth。但是在启动时手动添加此路径并不能修复以python -m plinth运行时的ImportError。在

我正在运行以下代码:https://github.com/freedombox/Plinth/tree/0b5af376102f4210395c15b2366b96a6e56fefb2

更新
感谢@cyraxjoe,os.chdir()加上__init__.py中丢失的模块是问题所在。对我来说,这种行为是出乎意料的,而且我没有找到很多有用的信息/文档,所以我设置了一个github repo来更容易地演示这个问题:https://github.com/fonfon/ImportError-demo


Tags: pathdjangopyhttpsgithubmoduleshomesys
1条回答
网友
1楼 · 发布于 2024-10-03 06:30:40

这只是一个理论,但可能是原因。在

鉴于:

  1. 去监视器插件changes the directory to the rootos.chdir('/')。在
  2. plinth.modules.first_boot显式导入first_boot,而不是包的__init__.py上的中间件。在

可能是在守护程序插件更改目录之前,导入了模块plinth.modules.first_boot,但没有中间件,因此,当django y尝试动态导入模块时,它只是在导入缓存中找到模块,但它找不到中间件,因为路径是相对的,当守护程序插件更改目录时,它就变得不可访问。在

尝试导入包的__init__上的中间件模块。在

基本上在^{}上添加一个from . import middleware

相关问题 更多 >