与QProcess Python程序进行通信 [英] Communicating with QProcess Python program

查看:288
本文介绍了与QProcess Python程序进行通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取Qt应用程序以与python程序进行通信.最合乎逻辑的解决方案似乎是在包含Python代码的Qt应用程序中运行QProcess.我想使用std输入发送命令,如果适用,可以通过std输出读取.

I'm trying to get a Qt application to communicate with a python program. The most logical solution seemed to be to run a QProcess in the Qt app containing the Python code. I want to send commands using std input and if applicable read via the std output.

但是,即使这个简单的例子似乎也不起作用.这两个python片段:

However, even this simple example doesn't seem to work. These two python snippets:

import os
import time

while True:
    print "test"
    time.sleep(2)

连同简单的Qt代码:

MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
    process = new QProcess(this);
    process->start("/home/user/test.py");

    connect(process, SIGNAL(stateChanged(QProcess::ProcessState)), SLOT(printProcessStatus()));
    connect(process, SIGNAL(error(QProcess::ProcessError)), SLOT(printProcessError()));
    connect(process, SIGNAL(readyRead()), SLOT(printProcessOutput()));
}

void MainWindow::printProcessStatus()
{
    qDebug() << process->state();
}

void MainWindow::printProcessError()
{
    qDebug() << process->errorString();
}

void MainWindow::printProcessOutput()
{
    qDebug() << process->readAll();
}

不打印任何内容.它确实说该过程是"QProcess :: ProcessState(Running)",但是我似乎无法将python的打印输出输出到Qt中.同样,我尝试使用QProcess :: write()函数写入python进程,但这也不起作用.

Doesn't print anything. It does say that the process is "QProcess::ProcessState(Running)", but I can't seem to get the printed output from python into Qt. Similarly I've tried to use the QProcess::write() function to write to a python process but that doesn't work either.

这不是使用QProcess的预期方式吗?有没有更好的方法可以在Qt应用程序和(子)python程序之间进行通信?

Is this not the intended way to work with QProcess? Is there a better way to do communication between a Qt app and a (child) python program?

推荐答案

问题似乎出在python缓冲stdout的方式(不是行缓冲).如果我将脚本更改为...,那么您发布的代码将对我有用.

The problem appears to be the way in which python buffers stdout (it's not line buffered). The code you posted works for me if I change the script to...

#!/usr/bin/env python2
import os
import sys
import time

while True:
    print "test"
    sys.stdout.flush()
    time.sleep(2)

也许有一种更好的方法可以实现相同的目的,而不必不断显式刷新流.

There's probably a better way to achieve the same thing without having to explicitly flush the stream constantly.

或者,如果您使用的是Linux,则可以使用 stdbuf 来控制脚本的输出缓冲.将process start命令更改为...

Alternatively, if you are on Linux, you could use stdbuf to control the output buffering of the script. Change the process start command to...

process->start("stdbuf", QStringList() << "--output=L" << "/home/user/test.py");

这篇关于与QProcess Python程序进行通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆