【问题标题】:How to use output of childprocess in called process without terminating child process?如何在不终止子进程的情况下在被调用进程中使用子进程的输出?
【发布时间】:2014-04-01 23:11:20
【问题描述】:

我在 python 中创建了两个模块。其中一个模块用于使用 Tkinter 创建 GUI,第二个模块用于捕获和存储图像。当我在 Tkinter 模块中调用 opencv 模块时,它首先运行 opencv 模块,释放相机后,它正在运行 Tkinter 模块。所以我使用了子进程。弹出()。现在我想将子进程输出到 Tkinter 模块中。使用Tkinter创建GUI的代码如下。

import sys
from Tkinter import *
import Tkinter
import subprocess
def capcam():
    command="python2 imacap.py"
    subprocess.Popen(command,shell=True)
root=Tk()
add=Frame(root)
add.grid()
root.title("Test")
capcam()
button_height=11
button_width=29
button_ipadx=2
button_ipady=2
text_box = Entry(add,justify=RIGHT,width=100, font=100)
text_box.grid(row = 0, column = 1,columnspan = 5)
text_box.insert(0, "0")
bttn_3 = Button(add, height= button_height ,width= button_width,text = "3")
bttn_3.grid(row = 3, column = 2, padx=button_ipadx, pady=button_ipady)

以下是子进程的代码。

import cv2.cv as cv
capture = cv.CaptureFromCAM(0)
num = 0
while True:
    img = cv.QueryFrame(capture)
    cv.SaveImage('pic'+str(num)+'.jpg', img)
    if num == 500:
        del(capture)
        break
    if cv.WaitKey(10) == 27:
        break
    num += 1

我想要主进程中运行时 num 变量的值,并希望将其传递给条目而不终止子进程。

【问题讨论】:

  • 这里不需要子进程。您可以使用threadingmultiprocessing 运行来自imacap 模块的代码。

标签: opencv python-2.7 tkinter subprocess


【解决方案1】:

保持参考

p = subprocess.Popen(command,shell=True, stdout = subprocess.PIPE)

那你就可以了

num = int(p.stdout.readline()) # blocks!

如果你这样做

print(num) in the child process

还可以查看模块多处理。它可以通过其他方式解决问题。

【讨论】:

【解决方案2】:

Can I have Tk events handled while waiting for I/O? 展示了如何在从 GUI 线程读取子进程输出时避免阻塞。假设imacap.py 中有print(num)

def read_output(self, pipe, mask):
    data = os.read(pipe.fileno(), 1 << 20)
    if not data: # eof
        root.deletefilehandler(proc.stdout)
    else:
        print("got: %r" % data)

proc = Popen(["python2", "imacap.py"], stdout=PIPE, stderr=STDOUT)
root.createfilehandler(proc.stdout, READABLE, read_output)

完整的代码示例:tkinter-read-async-subprocess-output.py 演示了如何使用 Tkinter 在没有线程的情况下读取子进程输出。它在 GUI 中显示输出并在按下按钮时停止子进程。

如果tk.createfilehandler() 在您的系统上不起作用;您可以尝试改用后台线程。代码示例见kill-process.py

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-07
  • 1970-01-01
  • 2012-11-13
  • 2019-06-03
  • 1970-01-01
  • 2021-07-12
  • 1970-01-01
相关资源
最近更新 更多