【发布时间】:2018-04-20 08:09:53
【问题描述】:
我在从 QProcess 执行 python3 脚本时遇到了这个问题。 python 脚本从一秒到一秒地打印时间,从命令行运行良好。在 Qt 中,信号 readyReadStandardOutput() 连接到调用 readAllStandardOutput() 以从脚本读取标准输出的插槽。 问题是槽只被调用一次!它打印一次时间,然后不再打印。 QProcess 的状态保持在“运行” 状态。永远不会调用 readyReadStandardError() 和 error(QProcess::ProcessError) 信号。
为什么必须每秒调用一次插槽?谢谢
Python 脚本:
import time, threading
def foo():
print(time.ctime())
threading.Timer(1, foo).start()
foo()
Qt:
MClass::MClass(QObject* parent)
{
m_process = new QProcess(this);
connect(m_process, SIGNAL(readyReadStandardOutput()), this, SLOT(onTest()));
connect(m_process, SIGNAL(readyReadStandardError()), this, SLOT(onTestErr()));
connect(m_process, SIGNAL(error(QProcess::ProcessError)), this, SLOT(onTestErr()));
connect(m_process, SIGNAL(stateChanged(QProcess::ProcessState)), this, SLOT(onTestState()));
startProcess();
}
void MClass::startProcess()
{
QString script= "../../python/test.py";
QString pythonCommand = "python3 " + script;
printf("PyCommand: %s\n", pythonCommand.toStdString().c_str());
m_process->start(pythonCommand);
// m_process->start("python3", QStringList()<<script);
}
}
void MClass::onTest()
{
qDebug()<<"------------------ON TEST";
while(m_process->canReadLine())
{
qDebug()<<m_process->readAllStandardOutput();
}
}
void MClass::onTestErr()
{
qDebug()<<"------------------ON ERR: " << m_process->errorString();
}
void MClass::onTestState()
{
qDebug()<<"------------------ STATE CHANGED: " << m_process->state();
}
【问题讨论】:
-
我们可以看看你的python脚本吗?它是一个交互式脚本,即您是否从标准输入中读取?它可以解释为什么进程保持运行。
-
@jbh python脚本在qt代码上方
-
-
@S.Monteleone 它没有任何区别
-
在我看来,这种行为的原因是只有第一个打印在主线程中执行,其他线程在其他线程中执行。
标签: python c++ qt qt5 qprocess