请考虑以下测试用例。
项目目录的结构如下:
foo
├── foo
│ ├── __init__.py
│ └── bar.py
└── test.tac
bar.py
包含一个简单的类定义:
# bar.py
class Bar:
pass
test.tac
,Twisted Application Configuration文件,包含一个import语句:
#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>
则不会。
twistd
有这么好的理由?twistd
中修复此问题的建议方法是什么?我可以设置某种选项,还是需要手动完成?答案 0 :(得分:0)
Python中没有规则说工作目录应该在路径上。相反,默认情况下,Python将主脚本的目录放在路径上。当您运行python test.tac
时,该目录是工作目录,但是当您运行twistd时,主Python脚本是Twisted的一部分,它不在工作目录中。
由于我不熟悉Twisted,我不能说你应该使用什么组合的代码组织和Twisted配置来使这个导入工作。
答案 1 :(得分:0)
此代码段会将包含tac文件的目录添加到python路径
for (int i = 0; i < ui->table->model->rowCount(); ++i) {
QString value = ui->table->model()->data(ui->table->model()->index(i, 1));
qDebug() << value;
}