PyQt4 QProcess.startDetached() - 无法获取生成进程的返回值和 PID [英] PyQt4 QProcess.startDetached() - can't get return value and PID of spawned process

查看:154
本文介绍了PyQt4 QProcess.startDetached() - 无法获取生成进程的返回值和 PID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是上一个问题的后续问题(再次由我发布):PyQt4 QProcess 状态始终为 0,各种插槽也无法正常工作

This is a follow-up question to a previous one (again posted by me): PyQt4 QProcess state always 0, various slots not working too

代码(修改):

主要应用:qprocess_test.py

#!/usr/bin/python

import sys
from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import QProcess


class Example(QtGui.QWidget):


    def __init__(self):
        super(Example, self).__init__()
        self.command = "./testCommand.py"
        self.args = [""]
        self.initUI()

    def initUI(self):               
        hbox = QtGui.QHBoxLayout()
        hbox.addStretch(1)

        qbtn = QtGui.QPushButton('Start', self)
        qbtn.clicked.connect(self.toggleProcess)
        qbtn.resize(qbtn.sizeHint())
        hbox.addWidget(qbtn)

        # This button is for testing the responsiveness of the GUI after the QProcess has been started
        qbtn2 = QtGui.QPushButton('Click me', self)
        qbtn2.setCheckable(True)
        qbtn2.toggled.connect(self.toggleButton)
        qbtn2.resize(qbtn2.sizeHint())
        hbox.addWidget(qbtn2)

        self.setLayout(hbox)
        self.setGeometry(300, 300, 250, 150)
        self.setWindowTitle('QProcess controlled by a button')    
        self.show()

    def toggleProcess(self):
        res, pid = QProcess.startDetached(self.command, self.args)
            print "Starting process\n", str(res), " | pid = ", str(pid)

    def toggleButton(self, value):
        if value == True:
            print "Lalalala!"
        else:
            print "Didadida!"

def main(): 
    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

现在 Start 按钮所做的就是启动分离的进程.这个想法是让它可切换并停止/启动分离的进程,只要用户根据 PID 与其交互.

For now all the Start button does is start the detached process. The idea is for it to be toggable and stop/start the detached process whenever the users interacts with it based on the PID.

用于创建进程的应用程序:testCommand.py

#!/usr/bin/env python

while True:
    print "a"

在做了一些阅读和谷歌搜索之后,我发现 startDetached() 函数在 Python 中返回 2 个值(在 C++ 中它是一个布尔函数,但它也设置了它的一个参数的值 - 指针 pid):

After doing some reading and googling I found out that the startDetached() function returns 2 values in Python (in the C++ it's a boolean function, but it also sets the value of one of its arguments - the pointer pid):

  • bool:告诉我们分离进程的启动是否成功
  • int:如果操作成功,则给出启动进程的PID

以下是我用于此信息的来源:

Here are the sources I have used for this information:

  • http://doc.qt.io/qt-4.8/qprocess.html#startDetached
  • http://pyqt.sourceforge.net/Docs/PyQt4/qprocess.html (due to current failure to load sourceforge properly here is the cached version: http://webcache.googleusercontent.com/search?q=cache:lQ-ixJIbVQQJ:pyqt.sourceforge.net/Docs/PyQt4/qprocess.html+&cd=1&hl=en&ct=clnk&gl=de&client=ubuntu)

出于某种原因,这根本不起作用.以下是我测试过的两种情况:

For some reason this is not working at all. Here are the two situations that I have tested:

  • 尝试从函数中获取 bool 和 int 值:

  • Trying to get both the bool and int values from the function:

res, pid = self.myProcess.startDetached(self.command, self.args)

我收到此错误:

Traceback (most recent call last):
  File "./qprocess_test.py", line 48, in toggleProcess
    res, pid = self.myProcess.startDetached(self.command, self.args)
TypeError: 'bool' object is not iterable

这告诉我我无法遍历 startDetached() 的返回值,因此实际上只返回一个 SINGLE 值,而不是两个,因为我在多段代码中也看到过PyQt4 文档...

This tells me that I can't iterate over the return value of startDetached() hence only a SINGLE value is actually returned and not two as I have also seen in multiple pieces of code again part of the PyQt4 documentation...

检查 startDetached() 实际返回的内容:它似乎只返回一个 int,我认为它是 PID.但是,如果是 PID,则它不是正确的值(查看 htop 的输出):

Checking what startDetached() actually returns: it seems it only returns an int, which I presume is the PID. However if it's the PID it is not the correct value (looking at the output of htop):

val = QProcess.startDetached(self.command, self.args)
# val = 0 (always!)

我了解到 startDetached() 是一个静态函数,因此与创建的进程的任何未来交互都可以通过它的 pid 完成,但调用其状态 (QProcess.state()) 等.是不可能的,因为没有要与之交互的对象.这个(损坏的)东西现在的工作方式确实是启动一个分离的进程,但由于我没有任何识别它的 PID,我唯一的交互方式是手动查找 testCommand.py 然后通过 kill 执行适当的信号.

I have learned that startDetached() is a static function hence any future interaction with the created process can be done via it's pid but things like calling its state (QProcess.state()) etc. are not possible since there is no object to interact with. The way this (broken) thing works right now is indeed start a detached process but since I don't have any PID that identifies it, the only way of interaction I have is finding manually the PID of the testCommand.py and then executing the appropriate signal via kill.

有谁知道我在这里做错了什么?我可以从基础开始使用 C/C++ 和各种系统调用,但我真的很想真正学习如何使用 PyQt4 和 Python 来做到这一点.

Does anyone know what I'm doing wrong here? I can go to the basics and start using C/C++ with the various system calls but I would really like to actually learn how to do this with PyQt4 and Python.

谢谢!

编辑

似乎 startDetached() 确实返回 True|False.然而,PID 无处可寻……不是在官方文档中读到的内容.

It seems that startDetached() indeed returns True|False. The PID however is nowhere to be found...Not what one reads in the official documentation.

推荐答案

startDetached 函数在 C++ 中被重载,它有几个签名.根据提供的参数,它不一定返回相同的内容.

The function startDetached is overloaded in C++, it has several signatures. Depending on the arguments provided, it does not necesseraly return the same thing.

即使 Python 中不存在重载,你也有类似的东西:

Even if overloading does not exist in Python, you have something similar:

import sys
from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import QProcess

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)

    command = "./testCommand.py"
    args = [""]

    #"regular" startDetached : give two arguments, get a boolean
    process=QProcess()
    re=process.startDetached("ls",["."])
    print(re)
    print(type(re))

    #"overload" startDetached : give three arguments, get a tuple(boolean,PID)
    process2=QProcess()
    re,pid=process2.startDetached("ls",["."],".")
    print(re,pid)
    print(type(re),type(pid))

这篇关于PyQt4 QProcess.startDetached() - 无法获取生成进程的返回值和 PID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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