gpt4 book ai didi

python - 没有来自 QProcess 的 readyReadStandardOutput 信号

转载 作者:太空宇宙 更新时间:2023-11-04 11:05:08 27 4
gpt4 key购买 nike

为什么我在运行以下命令时从未收到 readyReadStandardOutput 信号?

import os, sys, textwrap

from PyQt4 import QtGui, QtCore

out_file = open("sleep_loop.py", 'w')
out_file.write(textwrap.dedent("""
import time

while True:
print "sleeping..."
time.sleep(1)"""))
out_file.close()

def started():
print "started"

def on_error(error):
errors = ["Failed to start", "Crashed", "Timedout", "Read error",
"Write Error", "Unknown Error"]
print "error: ", errors[error]

def on_state_change(new_state):
states = ["Not running", "Starting", "Running"]
print "new state: ", states[new_state]

def on_out():
print "got out"

proc = QtCore.QProcess()
sig = QtCore.SIGNAL
proc.connect(proc, sig("started()"), started)
proc.connect(proc, sig("error(ProcessError)"), on_error)
proc.connect(proc, sig("readyReadStandardOutput()"), on_out)
proc.connect(proc, sig("stateChanged(ProcessState)"),
on_state_change)
proc.start("python sleep_loop.py")

app = QtGui.QApplication(sys.argv)
widget = QtGui.QWidget()
widget.show()
app.exec_()

proc.close()

最佳答案

这里有两个问题:

  1. 您应该在创建其他所有内容之前创建 QApplication 实例。
  2. 您的子进程正在缓冲其输出。

这里是固定的代码,只改变了两行:

  1. app = QApplication 移动到 proc = QProcess
  2. 之前
  3. 子进程现在有 sys.stdout.flush()

现在一切如您所愿:

import os, sys, textwrap

from PyQt4 import QtGui, QtCore

out_file = open("sleep_loop.py", 'w')
out_file.write(textwrap.dedent("""
import time, sys

while True:
print "sleeping..."
sys.stdout.flush()
time.sleep(1)"""))
out_file.close()

def started():
print "started"

def on_error(error):
errors = ["Failed to start", "Crashed", "Timedout", "Read error",
"Write Error", "Unknown Error"]
print "error: ", errors[error]

def on_state_change(new_state):
states = ["Not running", "Starting", "Running"]
print "new state: ", states[new_state]

def on_out():
print "got out"

app = QtGui.QApplication(sys.argv)
proc = QtCore.QProcess()
sig = QtCore.SIGNAL
proc.connect(proc, sig("started()"), started)
proc.connect(proc, sig("error(ProcessError)"), on_error)
proc.connect(proc, sig("readyReadStandardOutput()"), on_out)
proc.connect(proc, sig("stateChanged(ProcessState)"),
on_state_change)
proc.start("python sleep_loop.py")

widget = QtGui.QWidget()
widget.show()
app.exec_()

proc.close()

关于python - 没有来自 QProcess 的 readyReadStandardOutput 信号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1854247/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com