gpt4 book ai didi

python - 为什么 twistd 不能从当前工作目录中导入模块?

转载 作者:行者123 更新时间:2023-12-05 06:33:20 27 4
gpt4 key购买 nike

请考虑以下测试用例。

项目目录结构如下:

foo
├── foo
│   ├── __init__.py
│   └── bar.py
└── test.tac

bar.py包含一个简单的类定义:

# bar.py
class Bar:
pass

test.tac ,Twisted 应用程序配置文件,包含一个导入语句:

#test.tac
from foo.bar import Bar

运行时twistd -ny test.tac ,我收到以下错误:

$ twistd -ny test.tac
Unhandled Error
Traceback (most recent call last):
File "/Users/lthibault/.pyenv/versions/3.6.2/lib/python3.6/site-packages/twisted/application/app.py", line 674, in run
runApp(config)
File "/Users/lthibault/.pyenv/versions/3.6.2/lib/python3.6/site-packages/twisted/scripts/twistd.py", line 25, in runApp
runner.run()
File "/Users/lthibault/.pyenv/versions/3.6.2/lib/python3.6/site-packages/twisted/application/app.py", line 381, in run
self.application = self.createOrGetApplication()
File "/Users/lthibault/.pyenv/versions/3.6.2/lib/python3.6/site-packages/twisted/application/app.py", line 453, in createOrGetApplication
application = getApplication(self.config, passphrase)
--- <exception caught here> ---
File "/Users/lthibault/.pyenv/versions/3.6.2/lib/python3.6/site-packages/twisted/application/app.py", line 464, in getApplication
application = service.loadApplication(filename, style, passphrase)
File "/Users/lthibault/.pyenv/versions/3.6.2/lib/python3.6/site-packages/twisted/application/service.py", line 416, in loadApplication
application = sob.loadValueFromFile(filename, 'application')
File "/Users/lthibault/.pyenv/versions/3.6.2/lib/python3.6/site-packages/twisted/persisted/sob.py", line 177, in loadValueFromFile
eval(codeObj, d, d)
File "test.tac", line 1, in <module>
from foo.bar import Bar
builtins.ModuleNotFoundError: No module named 'foo'


Failed to load application: No module named 'foo'

这非常令人惊讶,因为 python test.tac不会产生错误。为了进一步调试,我修改了test.tac如下:

from sys import path
print(path)
from foo.bar import Bar

这表明正在运行 python <filename>在运行 twistd <filename> 时将当前工作目录添加到路径中没有。

我的问题有两个:

  1. 这是一个错误,还是有充分的理由 twistd以这种方式行事?
  2. twistd 中推荐的修复此问题的方法是什么? .我可以设置某种选项还是需要手动完成?

最佳答案

此代码段会将包含 tac 文件的目录添加到 python 路径

import os
import sys

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

from foo.bar import Bar

关于python - 为什么 twistd 不能从当前工作目录中导入模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50803916/

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