本文整理汇总了Python中multiprocessing.Pipe.send方法的典型用法代码示例。如果您正苦于以下问题:Python Pipe.send方法的具体用法?Python Pipe.send怎么用?Python Pipe.send使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类multiprocessing.Pipe
的用法示例。
在下文中一共展示了Pipe.send方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: ClientProcess
# 需要导入模块: from multiprocessing import Pipe [as 别名]
# 或者: from multiprocessing.Pipe import send [as 别名]
class ClientProcess(Process):
def __init__(self):
Process.__init__(self)
self.parent, self.child = Pipe()
self.state = Lock()
self.start()
def run(self):
while 1:
active_clients = self.child.recv()
self.state.acquire()
client_socket = socket.fromfd(reduction.recv_handle(self.child), socket.AF_INET, socket.SOCK_STREAM)
self.client_process(client_socket, active_clients)
self.state.release()
def client_process(self, sock, active_clients):
while 1:
data = protocol.recv(sock)
if not data:
return sock.close()
encryption = TripleDESCipher(data["key"])
if data["encryption"] == 1:
protocol.send(sock, (active_clients, encryption.encrypt(data["message"])))
else:
protocol.send(sock, (active_clients, encryption.decrypt(data["message"])))
def add_task(self):
if self.state.acquire(False):
self.parent.send(True)
self.state.release()
return True
return False
示例2: __init__
# 需要导入模块: from multiprocessing import Pipe [as 别名]
# 或者: from multiprocessing.Pipe import send [as 别名]
class gui:
""" A multithreaded handler for the coincidence-count GUI """
def __init__(self):
""" Constructor """
# Start up the GUI process and build the communication network
self.pipe, their_pipe = Pipe()
self.gui = Process(target=gui_head, name="gui_head", args=(their_pipe,))
self.gui.start()
def collect(self):
""" Collect all messages and act upon them """
messages = []
while self.pipe.poll(0):
messages.append(self.pipe.recv())
return messages
def send(self, key, value):
""" Send a message to the threaded GUI """
self.pipe.send((key, value))
def kill(self):
""" Send the message to shut down """
self.send("kill", None)
示例3: main
# 需要导入模块: from multiprocessing import Pipe [as 别名]
# 或者: from multiprocessing.Pipe import send [as 别名]
def main():
parent, child = Pipe()
e = TestTask(control_pipe=child)
uri = e.uris['rpc']
p = Process(target=e.run)
try:
p.start()
z = ZmqJsonRpcProxy(uri.replace('*', 'localhost'))
# Rather than calling the `hello_world` proxy method directly, we
# instead call the `spawn` attribute of the proxy method. This causes
# the proxy call to be performed using eventlet green threads. Here,
# `d` is an `eventlet.event.Event` instance, which can be queried for
# when the result is ready. The final result can be obtained by
# calling the event's `wait` method. By calling `eventlet.sleep`, we
# yield execution to the RPC green thread to check again for a
# response.
d = z.hello_world.spawn()
while not d.ready():
print 'Something is happening in the "main" thread!'
eventlet.sleep(0.5)
result = d.wait()
print 'result is ready:', result
assert(result == 'hello, world')
finally:
parent.send('shutdown')
time.sleep(0.1)
p.terminate()
del p
示例4: calculateArea
# 需要导入模块: from multiprocessing import Pipe [as 别名]
# 或者: from multiprocessing.Pipe import send [as 别名]
def calculateArea(feature,session_cookies,options):
"""
return:{
status {
"invalid" : invalid message;
"failed" : failed message;
"overlapped" : overlap message
}
data: {
total_area: 100 //exist if status_code = 1
other_area: 10 //exist if status_code = 1 and len(layers) > 0
layers: { //exist if status_code = 1 and len(layers) > 0
layer id: {
total_area: 12
areas:[
{area:1, properties:{
name:value
}}
]
}
}
}
}
"""
parent_conn,child_conn = Pipe(True)
p = Process(target=calculateAreaInProcess,args=(child_conn,))
p.daemon = True
p.start()
parent_conn.send([feature,session_cookies,options])
result = parent_conn.recv()
parent_conn.close()
#p.join()
#print("{}:get the area result from other process".format(datetime.now()))
return result
示例5: ProcessApplication
# 需要导入模块: from multiprocessing import Pipe [as 别名]
# 或者: from multiprocessing.Pipe import send [as 别名]
class ProcessApplication(Application):
"""Run application class in subprocess."""
def __init__(self, reaktor, target, name=''):
Application.__init__(self, None, name)
self.target = target
self._reaktor = reaktor
self._process = None
self.parent = None
self.child = None
self.transport = None
self.runner = None
def start(self):
signal.signal(signal.SIGCHLD, self._sigchld)
self.parent, self.child = Pipe(duplex=True)
logging.debug("parent conn %d, child %d",
self.parent.fileno(), self.child.fileno())
self.transport = ConnectedTransport(self._reaktor, self.parent, self)
self.runner = _Subprocess(self.target, self.child, self.config)
self._process = Process(target=self.runner.run)
self._process.start()
def _close(self, timeout):
self._process.join(timeout)
if self.transport is not None:
# this closes also parent channel
self.transport.close()
self.transport.del_channel()
self.child = self.parent = self.transport = None
def _sigchld(self, signum, frame):
self._close(0.5)
def stop(self):
self._process.terminate()
self._close(2.0)
def send(self, data):
"""Send data to application."""
self.parent.send(data)
def recv(self, data):
"""Handle data received from subprocess application."""
if isinstance(data, Exception):
self.log.error("Subprocess exception: %s", str(data))
raise data
self.received(data)
def event_readable(self, transport):
assert(transport == self.transport)
data = self.transport.socket.recv()
self.log.debug("received from app: %s", str(data))
if data is not None:
self.recv(data)
def event_error(self, transport):
typ, ex, tb = sys.exc_info()
if typ != KeyboardInterrupt:
self.log.debug("process: %s", str(ex))
示例6: __init__
# 需要导入模块: from multiprocessing import Pipe [as 别名]
# 或者: from multiprocessing.Pipe import send [as 别名]
class DataPicker:
"""
Class to flush data on a link, it continuously read the data received on a link,
and return the last on get_data call.
"""
def __init__(self, pipe_in):
self.pipe_in = pipe_in
self.parent, self.child = Pipe()
self.proc = Process(target=self.start, args=(self.child,))
self.proc.start()
def start(self, child):
try:
while True:
data_in = self.pipe_in.recv()
# print "DATA_IN: ", data_in
if child.poll():
data = child.recv()
if data == "break":
break
child.send(data_in)
except KeyboardInterrupt:
self.close()
def get_data(self):
self.parent.send('ok')
data = self.parent.recv()
return data
def close(self):
self.parent.send("break")
示例7: ConsoleProxy
# 需要导入模块: from multiprocessing import Pipe [as 别名]
# 或者: from multiprocessing.Pipe import send [as 别名]
class ConsoleProxy(object):
def __init__(self):
self._read, self._write = Pipe(duplex=True)
def fileno(self):
return self._read.fileno()
def read(self):
data = self._read.recv()
if data["type"] == "completer":
result = command_root.match(data["line"], data["hints"])
elif data["type"] == "parser":
try:
result = command_root.parse(data["line"])
except Command.NotFound as e:
if str(e) != "":
result = str(e)
else:
result = "No such command '{:s}'".format(data["line"])
except Command.SyntaxError as e:
result = str(e)
else:
result = ""
self._read.send(result)
def completer(self, line, hints):
self._write.send({"type" : "completer", "line" : line, "hints" : hints})
return self._write.recv()
def parser(self, line):
self._write.send({"type" : "parser", "line" : line})
return self._write.recv()
示例8: MPPlugin
# 需要导入模块: from multiprocessing import Pipe [as 别名]
# 或者: from multiprocessing.Pipe import send [as 别名]
class MPPlugin(object):
# this functionality needs to be implemented in the cython parent side
def __init__(self):
self.plot_pipe, plotter_pipe = Pipe()
self.plotter = SimplePlotter(20000.)
self.plot_process = Process(target=self.plotter,
args=(plotter_pipe, ))
self.plot_process.daemon = True
self.plot_process.start()
def bufferfunction(self, n_arr=None, finished=False):
# print "entering plot"
send = self.plot_pipe.send
if finished:
send(None)
else:
# print "sending data"
if not n_arr:
n_arr = np.random.random((11, 1000))
send({'data': n_arr})
while 1:
if not self.plot_pipe.poll():
break
e = self.plot_pipe.recv()
print(e)
def setparam(self, name, value):
self.plot_pipe.send({'param': {name: value}})
示例9: recog_proc
# 需要导入模块: from multiprocessing import Pipe [as 别名]
# 或者: from multiprocessing.Pipe import send [as 别名]
def recog_proc(self, child_recog: Pipe, e_recog: Event, yolo_type: str):
"""
Parallel process for object recognition
Arguments:
child_recog {Pipe} -- pipe for communication with parent process,
sends bbox yolo type of recognized object
e_recog {Event} -- event for indicating complete recognize in frame
"""
# initialize YOLO
yolo = Yolo(yolo_type)
e_recog.set()
print("yolo defined")
while True:
frame = child_recog.recv()
print("recog process frame recieved")
if frame is None:
print("FRAME NONE? R U SURE ABOUT THAT?!")
return
res = yolo.detect(frame, cvmat=True)
print("recog send")
e_recog.set()
child_recog.send(res)
示例10: onExeBtn
# 需要导入模块: from multiprocessing import Pipe [as 别名]
# 或者: from multiprocessing.Pipe import send [as 别名]
def onExeBtn(self, event):
srcFiles = self.projPane.getValue()
self.analyzerOutDir = os.path.join(self.projRootDir, 'analyzer_output')
oldcwd = os.getcwd()
if not os.path.exists(self.analyzerOutDir):
os.makedirs(self.analyzerOutDir)
os.chdir(self.analyzerOutDir)
rcv_pipe, snd_pipe = Pipe(duplex=True)
self.dbname = ''.join([self.projRootDir.replace(os.sep, '_').strip('_'), '.sqlite'])
self.exePane.dbPathTc.SetValue(os.path.join(self.analyzerOutDir, self.dbname))
self.exePane.ppLogFileTc.SetValue(os.path.join(self.analyzerOutDir, 'preprocessor.log'))
self.exePane.parserLogFileTc.SetValue(os.path.join(self.analyzerOutDir, 'parser.log'))
p = Process(target=analyze,
args=(snd_pipe,
os.path.join(self.analyzerOutDir, self.dbname),
self.getPpCfg(),
self.getParserCfg(),
srcFiles,
self.exePane.pipelineCb.GetValue(),
self.exePane.numProcSc.GetValue(),
self.exePane.numPpProcSc.GetValue(),
self.exePane.numParserProcSc.GetValue(),
))
p.start()
dlg = wx.ProgressDialog('Executing',
'0/%d' % len(srcFiles),
parent=self,
maximum=len(srcFiles)*10,
style=wx.PD_CAN_ABORT |
wx.PD_APP_MODAL |
wx.PD_ELAPSED_TIME
)
dlg.SetSize((500,150))
dlg.Layout()
dlg.Show()
result = None
while True:
i, total, result = rcv_pipe.recv()
ret = dlg.Update(i*10, result if i == total else '[%d/%d] %s ... done' % (i+1, total, result))
if ret[0] == False:
rcv_pipe.send('STOP')
while result != 'STOPPED':
result = rcv_pipe.recv()
dlg.Update(total*10, 'Canceled')
break
if i == total:
break
p.join()
self.exePane.dbPathTc.SetValue(os.path.join(self.analyzerOutDir, self.dbname))
os.chdir(oldcwd)
示例11: main
# 需要导入模块: from multiprocessing import Pipe [as 别名]
# 或者: from multiprocessing.Pipe import send [as 别名]
def main():
logging.basicConfig(level=logging.INFO)
args = parse_args()
print args
echo_server = Process(target=EchoServer('ipc://ECHO:1',
args.echo_delay).run)
client = Process(target=JsonClient('ipc://PRODUCER_REP:1',
'ipc://PRODUCER_PUB:1',
args.request_count,
request_delay=args.request_delay).run)
parent_pipe, child_pipe = Pipe(duplex=True)
async_server_adapter = Process(
target=AsyncJsonServerAdapter('ipc://ECHO:1', 'ipc://PRODUCER_REP:1',
'ipc://PRODUCER_PUB:1', child_pipe).run
)
try:
echo_server.start()
async_server_adapter.start()
client.start()
client.join()
parent_pipe.send('close')
async_server_adapter.join()
except KeyboardInterrupt:
pass
client.terminate()
async_server_adapter.terminate()
echo_server.terminate()
# Since ipc:// creates files, delete them on exit
cleanup_ipc_uris(('ipc://ECHO:1', 'ipc://PRODUCER_REP:1',
'ipc://PRODUCER_PUB:1'))
示例12: master
# 需要导入模块: from multiprocessing import Pipe [as 别名]
# 或者: from multiprocessing.Pipe import send [as 别名]
def master():
results = []
mcn, scn = Pipe()
mon = Thread(target=monitor, args=(mcn, results))
mon.daemon = True
mon.start()
proc = Process(target=slave, args=(scn,))
proc.start()
mcn.send('1')
while not results:
time.sleep(0.01)
pid = results.pop()
log.info('pid: %s', pid)
mcn.send('die')
try:
for n in range(7):
if mcn.poll(1):
break
if not proc.is_alive():
raise Exception('stop')
except Exception:
log.error('slave died', exc_info=True)
示例13: ProcessStarter
# 需要导入模块: from multiprocessing import Pipe [as 别名]
# 或者: from multiprocessing.Pipe import send [as 别名]
class ProcessStarter(object):
def __init__(self):
'''
Setup the shared memory data structure model and initialize the control parts.
'''
self.running = True
self.orprocess = None
self.guiprocess = None
self.pipeGUI, self.pipeOR = Pipe()
self.StartProcesses()
def StartProcesses(self):
self.guiprocess = Process(target=self.__startGUI__)
self.guiprocess.start()
self.pipeGUI.send(["StartViewer", None])
self.orprocess = Process(target=ORServer,args=(self.pipeOR,))
self.orprocess.start()
return True
def terminate(self):
try:
self.pipeGUI.send(["Stop", None])
self.guiprocess.terminate()
self.orprocess.terminate()
except:
pass
def __startGUI__(self):
app = QtGui.QApplication(sys.argv)
form = pnpApp(self.pipeGUI, self)
form.show()
sys.exit(app.exec_())
示例14: ActiveConn
# 需要导入模块: from multiprocessing import Pipe [as 别名]
# 或者: from multiprocessing.Pipe import send [as 别名]
class ActiveConn(object):
"""
Talks to the specific backend instance associated with a userid
"""
def __init__(self, userid, modules):
self.userid = userid
self.here, self.there = Pipe(duplex=True)
self.proc = CoqProc()
self.proc.start(modules)
self.read()
logging.debug("Coqtop Process started %s", self.proc)
def read(self):
"""poll results from the coqtop backend"""
res = None
self.proc.run(self.there)
if self.here.poll():
res = self.here.recv()
logging.debug("Received content from process")
return {'userid': self.userid, 'response': res}
def send(self, data):
"""send results to our coqtop instance"""
if self.proc.alive:
logging.debug("sending stuff")
self.here.send(data + " ")
return True
else:
return False
def quit(self):
if self.proc.alive:
return self.proc.terminate(True)
示例15: __init__
# 需要导入模块: from multiprocessing import Pipe [as 别名]
# 或者: from multiprocessing.Pipe import send [as 别名]
class StubExecuteTestsFunc:
def __init__(self):
self.main_conn, self.func_conn = Pipe()
self._called = self._complete = None
self.stub_reset()
def stub_reset(self):
self._called = self._complete = False
def stub_complete(self):
self._complete = True
self.main_conn.send(StubExecuteTestsFuncConnMessages.COMPLETE)
def stub_called(self):
if not self._called and self.main_conn.poll():
conn_message = self.main_conn.recv()
if conn_message == StubExecuteTestsFuncConnMessages.CALLED:
self._called = True
return self._called
def __enter__(self):
self.stub_reset()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.stub_complete()
def __call__(self, *_):
self._called = True
self.func_conn.send(StubExecuteTestsFuncConnMessages.CALLED)
while not self._complete:
conn_message = self.func_conn.recv()
if conn_message == StubExecuteTestsFuncConnMessages.COMPLETE:
self._complete = True