我正在关注 http://pythonqt.sourceforge.net/Examples.html 中的示例,但 PythonQt 不会在控制台上打印任何内容。我执行了一个只打印 hello
的脚本,但没有打印任何内容。
PythonQt::init();
PythonQtObjectPtr context = PythonQt::self()->getMainModule();
context.evalScript("print 'hello'\n");
另一方面,如果我使用纯 python 嵌入执行它,它会工作并且打印 hello
:
Py_Initialize();
PyRun_SimpleString("print 'hello'\n");
有趣的是,如果我在 Py_Initialize();
之前添加 PythonQt::init();
,则不会再打印任何内容。所以我假设 PythonQt::init();
对 python 的控制台输出做了一些事情。它会以某种方式重定向它吗?如何打印?
我正在使用 Qt 4.8.6、PythonQt 2.1 和 Python 2.7.6。
最佳答案
看完https://sourceforge.net/p/pythonqt/discussion/631393/thread/33ad915c ,似乎 PythonQt::init();
确实将 python 输出重定向到 PythonQt::pythonStdOut 信号。
这是因为 PythonQt::init()
声明默认设置了 RedirectStdOut
:
static void init(int flags = IgnoreSiteModule | RedirectStdOut, const QByteArray& pythonQtModuleName = QByteArray());
所以这现在可以工作了:
PythonQt::init(PythonQt::IgnoreSiteModule);
PythonQtObjectPtr context = PythonQt::self()->getMainModule();
context.evalScript("print 'hello'\n");
或者,我可以连接信号:
QObject::connect(PythonQt::self(), SIGNAL(pythonStdOut(const QString&)), this, SLOT(Print(const QString&)));
关于PythonQt 不打印任何东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39214773/