def search_mv(s,user):
url = "http://music.163.com/api/search/get/"
postdata =urllib.parse.urlencode({
's':s,
'offset':'1',
'limit':'10',
'type':'1004'
}).encode('utf-8')
header = {
"Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Encoding":"utf-8",
"Accept-Language":"zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3",
"Connection":"keep-alive",
"Host":"music.163.com",
"Referer":"http://music.163.com/",
"User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0"
}
req = urllib.request.Request(url,postdata,header) #??????
result = json.loads(urllib.request.urlopen(req).read().decode('utf-8')) #????
result_id = result['result']['mvs'][0]['id'] #??mv id
_thread.start_new_thread(get_download_url, (result_id, 'mv', user,s)) #????????
#????????
python类start_new_thread()的实例源码
def main():
print('starting --',ctime())
locks = []
nloops = range(len(loops))
for i in nloops:
lock = _thread.allocate_lock() # ?????
lock.acquire() # ?????
locks.append(lock)
for i in nloops:
_thread.start_new_thread(loop,(i,loops[i],locks[i]))
for i in nloops:
while locks[i].locked():
pass
print('all Done---',ctime())
def _setUp(self):
self.server_ready = threading.Event()
self.client_ready = threading.Event()
self.done = threading.Event()
self.queue = queue.Queue(1)
self.server_crashed = False
# Do some munging to start the client test.
methodname = self.id()
i = methodname.rfind('.')
methodname = methodname[i+1:]
test_method = getattr(self, '_' + methodname)
self.client_thread = thread.start_new_thread(
self.clientRun, (test_method,))
try:
self.__setUp()
except:
self.server_crashed = True
raise
finally:
self.server_ready.set()
self.client_ready.wait()
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:
import traceback
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 receive_data(self):
# Start New Thread for pyPort object that can receive data and put it
# by queue
thread.start_new_thread(self.pyPort.receive_data,())
# Start New thread for plain text updating data when come from devices
thread.start_new_thread(self.refresh_plain_text,())
# To Add Data to Plain Text
# When queue added to pyPort.dataQueue it added
# to received_data and emit signal
def start_thread(function, *args, **kwargs):
"Start a new thread and wrap with error catching."
_thread.start_new_thread(_bootstrap, (function, args, kwargs))
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',))
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 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 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',))