Sending and receiving async over multiprocessing.Pipe() in Python

社会主义新天地 提交于 2020-01-13 05:17:06

问题


I'm having some issues getting the Pipe.send to work in this code. What I would ultimately like to do is send and receive messages to and from the foreign process while its running in a fork. This is eventually going to be integrated into a pexpect loop for talking to interpreter processes.

from multiprocessing import Process, Pipe
from pexpect import spawn


class CockProc(Process):

    def start(self):
        self.process = spawn('coqtop', ['-emacs-U'])

    def run(self, conn):
        while True:
            if not conn.poll():
                cmd = conn.recv()
                self.process.send(cmd)
            self.process.expect('\<\/prompt\>')
            result = self.process.before + self.process.after + " "
            conn.send(result)


q, p = Pipe()

proc = CockProc()
proc.start()
proc.run(p)
res = q.recv()
command = raw_input(res + " ")

q.send(command)
res = q.recv()
parent_conn.send('OHHAI')
p.join()
    `

回答1:


This works, but might need some more work. Not sure how many of these i can create and loop over.

from multiprocessing import Process, Pipe
from pexpect import spawn


class CockProc(Process):

    def start(self):
        self.process = spawn('coqtop', ['-emacs-U'])

    def run(self, conn):
        if conn.poll():
            cmd = conn.recv()
            self.process.send(cmd + "\n")
            print "sent comm"
        self.process.expect('\<\/prompt\>')
        result = self.process.before + self.process.after + " "
        conn.send(result)

here, there = Pipe(duplex=True)

proc = CockProc()
proc.start()
proc.run(there)

while True:
    if here.poll():
        res = here.recv()
        command = raw_input(res + " ")
        here.send(command)
    proc.run(there)


来源:https://stackoverflow.com/questions/2831299/sending-and-receiving-async-over-multiprocessing-pipe-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!