62 lines
2 KiB
C++
62 lines
2 KiB
C++
|
|
|
|
#include "pythonembed.h"
|
|
#include <QDebug>
|
|
|
|
PythonEmbed::PythonEmbed(QTextEdit* outputWidget, QObject* parent)
|
|
: QObject(parent), m_outputWidget(outputWidget), m_process(nullptr) {
|
|
m_process = new QProcess(this);
|
|
connect(m_process, &QProcess::readyReadStandardOutput, this, &PythonEmbed::onOutputAvailable);
|
|
connect(m_process, &QProcess::readyReadStandardError, this, &PythonEmbed::onErrorAvailable);
|
|
connect(m_process, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), this, &PythonEmbed::onProcessFinished);
|
|
}
|
|
|
|
PythonEmbed::~PythonEmbed() {
|
|
if (m_process) {
|
|
m_process->terminate();
|
|
m_process->waitForFinished(1000);
|
|
}
|
|
}
|
|
|
|
void PythonEmbed::runScript(const QString& scriptContent) {
|
|
if (m_process->state() == QProcess::Running) {
|
|
m_process->terminate();
|
|
m_process->waitForFinished(1000);
|
|
}
|
|
|
|
m_outputWidget->clear();
|
|
m_outputWidget->append("Python 3.11.2 (main, Oct 5 2023, 17:20:59) [GCC 11.4.0] on linux\n");
|
|
m_outputWidget->append("Type \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n\n");
|
|
|
|
m_process->start("python3", QStringList() << "-c" << scriptContent);
|
|
}
|
|
|
|
void PythonEmbed::stopScript() {
|
|
if (m_process && m_process->state() == QProcess::Running) {
|
|
m_process->terminate();
|
|
}
|
|
}
|
|
|
|
void PythonEmbed::onOutputAvailable() {
|
|
QByteArray output = m_process->readAllStandardOutput();
|
|
m_outputWidget->append(output);
|
|
m_outputWidget->moveCursor(QTextCursor::End);
|
|
}
|
|
|
|
void PythonEmbed::onErrorAvailable() {
|
|
QByteArray error = m_process->readAllStandardError();
|
|
m_outputWidget->append(error);
|
|
m_outputWidget->moveCursor(QTextCursor::End);
|
|
}
|
|
|
|
void PythonEmbed::onProcessFinished(int exitCode, QProcess::ExitStatus exitStatus) {
|
|
if (exitStatus == QProcess::NormalExit && exitCode != 0) {
|
|
m_outputWidget->append(QString("Process exited with code %1\n").arg(exitCode));
|
|
} else if (exitStatus == QProcess::CrashExit) {
|
|
m_outputWidget->append("Python process crashed\n");
|
|
}
|
|
}
|
|
|
|
#include "pythonembed.moc"
|
|
|