【发布时间】:2018-05-12 20:42:39
【问题描述】:
我想从 Qt 运行一个 python 脚本。我可以用QProcess 调用它并让qDebug() 打印python 脚本打印的内容。但由于某种原因,在代码中的某个点之后,我无法 Qt 读取任何 python 脚本的打印。
有人知道如何解决这个问题吗?非常感谢你。这是我在这里的第一个问题,如果我做错了什么,我很抱歉。
我的 widget.cpp 文件和 python 脚本如下。 (python 脚本在 Qt 程序的目录中。)
我的 widget.cpp 文件:
#include "widget.h"
#include "ui_widget.h"
#include "QDebug"
#include <QTimer>
#include <QProcess>
#include <QDir>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(checkTexts()));
timer->start(5000);
}
Widget::~Widget()
{
delete ui;
}
void Widget::checkTexts()
{
//QProcess process; //I also tried this way with the same results
QProcess *process = new QProcess(this);
QStringList arguments { QCoreApplication::applicationDirPath() + "/../../../../../Folder/Qt Desktop Application/ApplicationFiles/PullText.py"};
process->start("python", arguments);
process->waitForFinished(-1);
QString output = process->readAll();
process->close();
qDebug() << output;
}
我的 Python 脚本 (PullText.py) 应该向我的 Qt 应用程序发送一行文本文件:
newMessageSplitter = "***\n"
#print "1" #this prints in the qDebug() << output
file = open("texts.txt","r")
#print “2” #this doesn't print
texts = file.read()
x = texts.find(newMessageSplitter) + len(newMessageSplitter)
singleLine = texts[:x-len(newMessageSplitter)]
file.close()
file = open("texts.txt","w")
file.write(texts[x:])
file.close()
#print singleLine #this is what I want to send to the output but it doesn't get sent to Qt
【问题讨论】:
-
如果手动运行python脚本,是否有效?如果在第二次打印之前出错,您将看不到该输出
-
file.close或file.close()? -
python 脚本在我单独运行时可以正常运行。抱歉,file.close 是我的问题中的一个错字。
-
@Johnny 这是唯一的印刷错误?我想这种类型的错误不会再出现了,因为它们会导致无聊,而且我们不愿意帮助您,您可以指出项目路线、构建文件夹和 .py 文件之间的关系