def mt_interact(self):
"""Multithreaded version of interact()."""
import thread
thread.start_new_thread(self.listener, ())
while 1:
line = sys.stdin.readline()
if not line:
break
self.write(line)
python类start_new_thread()的实例源码
def start_new_thread(function, args, kwargs={}):
"""Dummy implementation of thread.start_new_thread().
Compatibility is maintained by making sure that ``args`` is a
tuple and ``kwargs`` is a dictionary. If an exception is raised
and it is SystemExit (which can be done by thread.exit()) it is
caught and nothing is done; all other exceptions are printed out
by using traceback.print_exc().
If the executed function calls interrupt_main the KeyboardInterrupt will be
raised when the function returns.
"""
if type(args) != type(tuple()):
raise TypeError("2nd arg must be a tuple")
if type(kwargs) != type(dict()):
raise TypeError("3rd arg must be a dict")
global _main
_main = False
try:
function(*args, **kwargs)
except SystemExit:
pass
except:
_traceback.print_exc()
_main = True
global _interrupt
if _interrupt:
_interrupt = False
raise KeyboardInterrupt
def interrupt_main():
"""Set _interrupt flag to True to have start_new_thread raise
KeyboardInterrupt upon exiting."""
if _main:
raise KeyboardInterrupt
else:
global _interrupt
_interrupt = True
def config_update(self, config):
self.config = config
self.mqtt_qos_publish = int(self.config['mqtt_qos_publish']) if 'mqtt_qos_publish' in config else 0
self.mqtt_qos_subscribe = int(self.config['mqtt_qos_subscribe']) if 'mqtt_qos_subscribe' in config else 0
self.mqtt_retain = 'mqtt_retain' in config and self.config['mqtt_retain']
if 'api_url' in config:
self.api_url = config['api_url']
thread.start_new_thread(self.api_login, ())
if self.mqtt_client:
self.mqtt_client.disconnect()
else:
self.mqtt_connect()
def stream_events_mongo(self, input_name, input_item, client, ew):
lt = LineTailer(client.admin)
try:
thread.start_new_thread( stream_logs, (lt, input_name, ew) )
except:
print "Error: unable to start thread"
def _start_request(self, req):
thread.start_new_thread(req.run, ())
def __init__(self, minSpare=1, maxSpare=5, maxThreads=sys.maxint):
self._minSpare = minSpare
self._maxSpare = maxSpare
self._maxThreads = max(minSpare, maxThreads)
self._lock = threading.Condition()
self._workQueue = []
self._idleCount = self._workerCount = maxSpare
# Start the minimum number of worker threads.
for i in range(maxSpare):
thread.start_new_thread(self._worker, ())
def addJob(self, job, allowQueuing=True):
"""
Adds a job to the work queue. The job object should have a run()
method. If allowQueuing is True (the default), the job will be
added to the work queue regardless if there are any idle threads
ready. (The only way for there to be no idle threads is if maxThreads
is some reasonable, finite limit.)
Otherwise, if allowQueuing is False, and there are no more idle
threads, the job will not be queued.
Returns True if the job was queued, False otherwise.
"""
self._lock.acquire()
try:
# Maintain minimum number of spares.
while self._idleCount < self._minSpare and \
self._workerCount < self._maxThreads:
self._workerCount += 1
self._idleCount += 1
thread.start_new_thread(self._worker, ())
# Hand off the job.
if self._idleCount or allowQueuing:
self._workQueue.append(job)
self._lock.notify()
return True
else:
return False
finally:
self._lock.release()
def start(self):
'Start the Proxy object.'
self.__lock.acquire()
self.__status = True
if not self.__thread:
self.__thread = True
_thread.start_new_thread(self.__proxy, ())
self.__lock.release()
def EndDialogAfter(self, timeOut):
#thread needed because win32gui does not expose SetTimer API
import thread
thread.start_new_thread(self.Timer, (timeOut, ))
def main():
try:
socket.socket().connect(('127.0.0.1', 80))
webbrowser.open('http://127.0.0.1/htbin/index.py')
except:
if len(sys.argv) > 1:
sys.argv[1] = '80'
else:
sys.argv.append('80')
thread.start_new_thread(CGIHTTPServer.test, ())
webbrowser.open('http://127.0.0.1/htbin/index.py')
s = socket.socket()
s.bind(('', 8080))
s.listen(1)
s.accept()
def start(self):
'Start the Mille_Timer object.'
self.__lock.acquire()
self.__status = True
if not self.__thread:
self.__thread = True
_thread.start_new_thread(self.__run, ())
self.__lock.release()
def __init__(self, ZSP):
'Initialize the Query/Reply Protocol object.'
self.__ZSP = ZSP
self.__error = None
self.__Q_anchor = []
self.__Q_packet = []
self.__R_anchor = {}
self.__Q_lock = _thread.allocate_lock()
self.__R_lock = _thread.allocate_lock()
_thread.start_new_thread(self.__thread, ())
def recv_Q(self, timeout=None):
'Receive one query.'
if self.__error:
raise self.__error
if timeout is not None:
if not isinstance(timeout, (float, int, long)):
raise TypeError, 'timeout must be of type float, int, or long'
if not timeout >= 0:
raise ValueError, 'timeout must be greater than or equal to 0'
self.__Q_lock.acquire()
try:
try:
if self.__Q_packet:
Q = True
ID, obj = self.__Q_packet.pop()
else:
Q = False
anchor = [_thread.allocate_lock()]
anchor[0].acquire()
self.__Q_anchor.append(anchor)
finally:
self.__Q_lock.release()
except AttributeError:
raise self.__error
if Q:
return ID, obj
if timeout:
_thread.start_new_thread(self.__Q_thread, (timeout, anchor))
anchor[0].acquire()
try:
Q = anchor[1]
except IndexError:
if self.__error:
raise self.__error
raise Warning
return Q
def recv_R(self, ID, timeout=None):
'Receive one reply.'
if self.__error:
raise self.__error
if timeout is not None:
if not isinstance(timeout, (float, int, long)):
raise TypeError, 'timeout must be of type float, int, or long'
if not timeout >= 0:
raise ValueError, 'timeout must be greater than or equal to 0'
anchor = [_thread.allocate_lock()]
anchor[0].acquire()
self.__R_lock.acquire()
try:
try:
self.__R_anchor[ID] = anchor
finally:
self.__R_lock.release()
except AttributeError:
raise self.__error
if timeout:
_thread.start_new_thread(self.__R_thread, (timeout, ID))
anchor[0].acquire()
try:
R = anchor[1]
except IndexError:
if self.__error:
raise self.__error
raise Warning
return R
def shutdown(self,sec,save=True,filepath='temp.h5'):
if save:
self.model.save(filepath, overwrite=True)
self.t_send('Command accepted,the model has already been saved,shutting down the computer....')
else:
self.t_send('Command accepted,shutting down the computer....')
if 'Windows' in platform.system():
th.start_new_thread(system, ('shutdown -s -t %d' %sec,))
else:
m=(int(sec/60) if int(sec/60) else 1)
th.start_new_thread(system, ('shutdown -h -t %d' %m,))
def cancel(self):
#Cancel function to cancel shutting down the computer
self.t_send('Command accepted,cancel shutting down the computer....')
if 'Windows' in platform.system():
th.start_new_thread(system, ('shutdown -a',))
else:
th.start_new_thread(system, ('shutdown -c',))
def on_epoch_end(self, epoch, logs=None):
for k in self.params['metrics']:
if k in logs:
self.mesg+=(k+': '+str(logs[k])[:5]+' ')
self.logs_epochs.setdefault(k, []).append(logs[k])
if epoch+1>=self.stopped_epoch:
self.model.stop_training = True
logs = logs or {}
self.epoch.append(epoch)
self.t_epochs.append(time.time()-self.t_s)
if self.savelog:
sio.savemat((self.fexten if self.fexten else self.validateTitle(self.localtime))+'_logs_batches'+'.mat',{'log':np.array(self.logs_batches)})
sio.savemat((self.fexten if self.fexten else self.validateTitle(self.localtime))+'_logs_batches'+'.mat',{'log':np.array(self.logs_epochs)})
th.start_new_thread(self.get_fig,())
self.t_send(self.mesg)
return
def shutdown(self,sec,save=True,filepath='temp.h5'):
if save:
self.model.save(filepath, overwrite=True)
self.t_send('Command accepted,the model has already been saved,shutting down the computer....')
else:
self.t_send('Command accepted,shutting down the computer....')
if 'Windows' in platform.system():
th.start_new_thread(system, ('shutdown -s -t %d' %sec,))
else:
m=(int(sec/60) if int(sec/60) else 1)
th.start_new_thread(system, ('shutdown -h -t %d' %m,))
def cancel(self):
#Cancel function to cancel shutting down the computer
self.t_send('Command accepted,cancel shutting down the computer....')
if 'Windows' in platform.system():
th.start_new_thread(system, ('shutdown -a',))
else:
th.start_new_thread(system, ('shutdown -c',))