本文整理汇总了Python中multiprocessing.Pipe.poll方法的典型用法代码示例。如果您正苦于以下问题:Python Pipe.poll方法的具体用法?Python Pipe.poll怎么用?Python Pipe.poll使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类multiprocessing.Pipe
的用法示例。
在下文中一共展示了Pipe.poll方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run
# 需要导入模块: from multiprocessing import Pipe [as 别名]
# 或者: from multiprocessing.Pipe import poll [as 别名]
def run(self):
if not self.isRunnable():
print "Can't run thread '{}'".format(self.name)
print self.target, self.EVT_ID, self.notifyWindow, self.process
return
try:
parentPipe, childPipe = Pipe()
#self.process = Process(target = self.target, args = (childPipe, self.args))
self.process = threading.Thread(target = self.target,
name = "Serial communication thread",
kwargs = {"pipe": childPipe,
"args": self.args})
self.process.name = self.name
self.process.daemon = True
self.process.start()
while self.process.isAlive() or parentPipe.poll(0.001):
if parentPipe.poll(0.001):
out = parentPipe.recv()
wx.PostEvent(self.notifyWindow, ResultEvent(out, self.EVT_ID))
if self.stop:
if self.stopSignalTime == 0:
self.stopSignalTime = time() + 0.5
parentPipe.send([False])
if time() > self.stopSignalTime:
self.process._Thread__stop()
wx.YieldIfNeeded()
#sleep(0.01)
except OSError, e:
wx.PostEvent(self.notifyWindow, ResultEvent(\
"Execution failed in thread '{}', message: {}".format(\
self.name, e), self.EVT_ID))
示例2: tempControlProcTest
# 需要导入模块: from multiprocessing import Pipe [as 别名]
# 或者: from multiprocessing.Pipe import poll [as 别名]
def tempControlProcTest(mode, cycle_time, duty_cycle, set_point, k_param, i_param, d_param, conn):
p = current_process()
print 'Starting:', p.name, p.pid
parent_conn_temp, child_conn_temp = Pipe()
ptemp = Process(name = "getrandProc", target=getrandProc, args=(child_conn_temp,))
#ptemp.daemon = True
ptemp.start()
parent_conn_heat, child_conn_heat = Pipe()
pheat = Process(name = "heatProctest", target=heatProctest, args=(cycle_time, duty_cycle, child_conn_heat))
#pheat.daemon = True
pheat.start()
while (True):
if parent_conn_temp.poll():
randnum = parent_conn_temp.recv() #non blocking receive
conn.send([randnum, mode, cycle_time, duty_cycle, set_point, k_param, i_param, d_param])
if parent_conn_heat.poll():
cycle_time, duty_cycle = parent_conn_heat.recv()
#duty_cycle = on_time/offtime*100.0
#cycle_time = on_time + off_time
if conn.poll():
mode, cycle_time, duty_cycle, set_point, k_param, i_param, d_param = conn.recv()
#conn.send([mode, cycle_time, duty_cycle])
#if mode == "manual":
parent_conn_heat.send([cycle_time, duty_cycle])
示例3: run_http_server
# 需要导入模块: from multiprocessing import Pipe [as 别名]
# 或者: from multiprocessing.Pipe import poll [as 别名]
def run_http_server(redirect_uri = None, modify_port = True, port_range = (10000, 10010) ):
"""Returns (modified) redirect_uri"""
from multiprocessing import Process, Pipe
from urllib.parse import urlsplit, urlunsplit
if redirect_uri is None:
redirect_uri = "http://localhost"
p = urlsplit(redirect_uri)
#Ensure hostname is localhost or 127.0.0.1
if p.hostname != "127.0.0.1" and p.hostname != "localhost":
raise ValueError("url must have host of 127.0.0.1 or localhost! Got: {}".format(p.hostname))
if not modify_port:
if p.port is not None:
port_range = (int(p.port), int(p.port))
else:
port_range = (int(80), int(80))
parent_port_pipe, child_port_pipe = Pipe()
parent_pipe, child_pipe = Pipe()
httpd_p = Process(target = _run_http_server, args = (child_port_pipe, child_pipe, port_range))
httpd_p.start()
if parent_port_pipe.poll(3000):
final_port = parent_port_pipe.recv()
else:
raise Exception("Timeout waiting for HTTP server process to start")
if final_port == 0:
#Could not find a port
raise Exception("Could not find open port")
netloc = "{0}:{1}".format(p.hostname, final_port)
if p.path:
path = p.path
else:
path = '/'
p = p._replace(netloc = netloc, path = path)
return (urlunsplit(p), parent_pipe, httpd_p)
示例4: run
# 需要导入模块: from multiprocessing import Pipe [as 别名]
# 或者: from multiprocessing.Pipe import poll [as 别名]
def run(self):
print self.obj.name() + " thinks..."
parent_conn, child_conn = Pipe()
self.process = AsyncRunProcess(self.obj, self.state, child_conn)
self.process.start()
while not self.stop and not parent_conn.poll():
time.sleep(0.1)
if self.stop:
self.process.terminate()
self.process.join()
elif parent_conn.poll():
msg, result = parent_conn.recv()
print "Calculation finished"
self.process.join()
self.emit(QtCore.SIGNAL("success"), result)
self.emit(QtCore.SIGNAL("finished"))
示例5: MMLWorker
# 需要导入模块: from multiprocessing import Pipe [as 别名]
# 或者: from multiprocessing.Pipe import poll [as 别名]
class MMLWorker(object):
"""Represents the Daemon's connection to the subprocess"""
def __init__(self,runner):
"""Creates and initalizes a subprocess and its connections."""
self.pipe, pipe = Pipe()
self.proc = Process(target=worker, args=(pipe,runner))
self.proc.start();
self.pid = self.proc.pid
def __del__(self):
"""Ensures the subprocess is correctly garbage collected."""
self.pipe.close();
self.proc.terminate();
def pump(self,block=False):
"""Returns a key,val pair from the subprocess, or None,None."""
key,val = None,None
if block:
(key,val) = self.pipe.recv()
elif self.pipe.poll():
(key,val) = self.pipe.recv()
return key,val
def stop(self):
"""Sends the stop signal to the subprocess."""
self.pipe.send(('stop',()))
def pause(self):
"""Sends the pause signal to the subprocess."""
self.pipe.send(('pause',()))
def start(self,program):
"""Sends the start signal to the subprocess."""
self.pipe.send(('start',(program,)))
示例6: __init__
# 需要导入模块: from multiprocessing import Pipe [as 别名]
# 或者: from multiprocessing.Pipe import poll [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
示例7: Airplay
# 需要导入模块: from multiprocessing import Pipe [as 别名]
# 或者: from multiprocessing.Pipe import poll [as 别名]
class Airplay():
def __init__(self, file):
self.metadata = AIRPLAY_DEFAULT
self.block = ''
self.out_pipe, self.in_pipe = Pipe()
p = Process(target=read_shairport_pipe, args=(file, self.in_pipe,))
p.start()
def __repr__(self):
printout = "metadata:\n"+self.metadata
# for k,v in self.metadata.items():
# printout += '%12s : %s\n' % (k,v)
return printout
def grab(self):
if self.out_pipe.poll(0):
s = True
self.metadata = self.out_pipe.recv() # prints "[42, None, 'hello']"
else:
print "nothing in pipe"
s = False
return s
示例8: evaluate_expression
# 需要导入模块: from multiprocessing import Pipe [as 别名]
# 或者: from multiprocessing.Pipe import poll [as 别名]
def evaluate_expression(exp):
'''
Evaluates given expression.
'''
if not exp:
return "No expression supplied."
exp = str(exp)
# Setup evaluation process if it's not present
global eval_process, eval_pipe_parent, eval_pipe_child
if not eval_process:
eval_pipe_parent, eval_pipe_child = Pipe()
eval_process = Process(name = "seejoo_eval",
target = _eval_worker,
args = (eval_pipe_child,))
eval_process.daemon = True
eval_process.start()
# Push expression through the pipe and wait for result
eval_pipe_parent.send(exp)
if eval_pipe_parent.poll(EVAL_TIMEOUT):
res = str(eval_pipe_parent.recv())
res = filter(lambda x: ord(x) >= 32, res) # Sanitize result
return res
# Evaluation timed out; kill the process and return error
os.kill(eval_process.pid, 9)
os.waitpid(eval_process.pid, os.WUNTRACED)
eval_process = None
return "Operation timed out."
示例9: dispatch
# 需要导入模块: from multiprocessing import Pipe [as 别名]
# 或者: from multiprocessing.Pipe import poll [as 别名]
def dispatch(self, fcn, timeout=0, params=()):
"""Start a new subrocess.
This function will detach 'fcn' as a process of its own,
passing params AND a pipe as arguments to 'fcn'.
If 'timeout' > 0 this function will block, waiting for the
detached process to send some data over the pipe.
If data i written to pipe in time, the pipe will be returned to the calling process.
On timeout, the pipe will be closed and 'None' will be returned to the calling process.
"""
conn, child_conn = Pipe()
p = Process(target=fcn, args=params + (child_conn,))
p.start()
if timeout > 0:
poll_status = conn.poll(timeout)
if poll_status == False:
print "Dispatched function %s did not send anything within the specified timeout (%d s)" % (fcn, timeout)
# FIXME: How to properly handle this case?
# - p.terminate() doesn't terminate any subprocesses the p might have spawned
# - conn.close(), i.e. closing the control channel, is probably better. Make sure p detects and handle it.
# - send a proper control message (set running to False) should work too.
# The proper way to implement a client is to handle connection.close() and stop running control message in the same way.
conn.close()
conn = None
return conn
示例10: run
# 需要导入模块: from multiprocessing import Pipe [as 别名]
# 或者: from multiprocessing.Pipe import poll [as 别名]
def run(self):
logging.info('Visualizer thread started')
parent_end, child_end = Pipe()
# Sensible default value for max_process
max_process = 3
process_count = 0
while not self.stop or not self.job_backlog.empty():
while parent_end.poll(0.1):
(name, counter) = parent_end.recv()
self.controller.find_trial(name).set_counter_plot(counter)
process_count -= 1
if self.job_backlog.empty():
time.sleep(1)
elif process_count < max_process:
process_count += 1
function, snapshot, trial = self.job_backlog.get_nowait()
logging.info('Visualizing {}'.format(trial.get_name()))
p = Process(target=self.render_graph,
args=(function, snapshot, trial.get_name(),
child_end))
p.start()
self.job_backlog.task_done()
logging.info('Visualizer Finished')
示例11: timeout
# 需要导入模块: from multiprocessing import Pipe [as 别名]
# 或者: from multiprocessing.Pipe import poll [as 别名]
def timeout(func, args=(), kwargs={}, timeout_duration=10):
"""This function will spawn a thread and run the given function
using the args, kwargs and return the given default value if the
timeout_duration is exceeded.
"""
class InterruptableProcess(Process):
def __init__(self, pipe):
Process.__init__(self)
self.pipe = pipe
def run(self):
result = func(*args, **kwargs)
self.pipe.send((result.installList, result.uninstallList, result.solvable))
parent_conn, child_conn = Pipe()
p = InterruptableProcess(child_conn)
p.start()
p.join(timeout_duration)
if p.is_alive():
p.terminate()
pass
if parent_conn.poll():
return parent_conn.recv()
else:
return None
示例12: __init__
# 需要导入模块: from multiprocessing import Pipe [as 别名]
# 或者: from multiprocessing.Pipe import poll [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)
示例13: ActiveConn
# 需要导入模块: from multiprocessing import Pipe [as 别名]
# 或者: from multiprocessing.Pipe import poll [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)
示例14: MPPlugin
# 需要导入模块: from multiprocessing import Pipe [as 别名]
# 或者: from multiprocessing.Pipe import poll [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}})
示例15: J1708
# 需要导入模块: from multiprocessing import Pipe [as 别名]
# 或者: from multiprocessing.Pipe import poll [as 别名]
class J1708():
def __init__(self,uart=None):
self._sport = None
if uart is not None:
self._sport = serial.Serial(port=uart,baudrate=9600,
bytesize=serial.EIGHTBITS,
stopbits=serial.STOPBITS_ONE)
self.buslock = Lock()
self.mypipe, self.otherpipe = Pipe()
self.r_proc = Process(target=run, args=(self._sport,self.buslock,self.otherpipe))
self.r_proc.start()
def read_message(self,timeout=None):
if not self.mypipe.poll(timeout):
return None
retval = self.mypipe.recv()
return retval
#currently relying on the read_thread to maintain synchronization
def send_message(self,msg):
retval = 0
thismsg = bytes(msg)
chksum = struct.pack('b',checksum(thismsg))
thismsg += chksum
with self.buslock:
retval = self._sport.write(thismsg)
self._sport.flushInput()#solve "echo" problem
return retval
def __del__(self):
self.r_proc.terminate()