我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用thread.exit()。
def GetUserCredentials(): """Prompts the user for a username and password.""" try: login = None password = None if login is None: login = rawInput("Login: ") if password is None: password = rawInput("Password: ", True) except (KeyboardInterrupt, SystemExit), e: if e.message: tools.exit(e.message) else: tools.exit return (login, password)
def confirm(message): printLine(message) try: while True: answer = rawInput("Yes/No: ") if answer.lower() in ["yes", "ye", "y"]: return True if answer.lower() in ["no", "n"]: return False failureMessage('Incorrect answer "%s", ' 'please try again:\n' % answer) except (KeyboardInterrupt, SystemExit), e: if e.message: tools.exit(e.message) else: tools.exit
def gpu_status(self,av_type_list): for t in av_type_list: cmd='nvidia-smi -q --display='+t #print('\nCMD:',cmd,'\n') r=os.popen(cmd) info=r.readlines() r.close() content = " ".join(info) #print('\ncontent:',content,'\n') index=content.find('Attached GPUs') s=content[index:].replace(' ','').rstrip('\n') self.t_send(s) time.sleep(.5) #th.exit() #============================================================================== # #==============================================================================
def __retrieveThread(optDic, taskCtrl, dummy): """ """ info(4,"Entering retrieveThread(%s) ..." % getThreadName()) client = ngamsPClient.ngamsPClient().\ parseSrvList(optDic["servers"][NGAS_OPT_VAL]) while (1): nextFileId = taskCtrl.getNextFileId() if (not nextFileId): thread.exit() nextFileId = nextFileId[:-1] stat = client.retrieve2File(nextFileId, targetFile=nextFileId) fileSize = getFileSize(nextFileId) taskCtrl.incBytesRecv(fileSize) info(1,"Next File ID: %s" % nextFileId)
def _registerThread(srvObj, fileListDbmName, tmpFilePat, diskInfoDic, reqPropsObj = None, dummyPar = None): """ See documentation for _registerExec(). The purpose of this function is merely to excapsulate the actual cloning to make it possible to clean up in case an exception is thrown. """ try: _registerExec(srvObj, fileListDbmName, tmpFilePat, diskInfoDic, reqPropsObj) rmFile(tmpFilePat + "*") thread.exit() except Exception: logger.exception("Exception raised in Register Sub-Thread") rmFile(tmpFilePat + "*") raise
def gpu_status(self,av_type_list): for t in av_type_list: cmd='nvidia-smi -q --display='+t #print('\nCMD:',cmd,'\n') r=os.popen(cmd) info=r.readlines() r.close() content = " ".join(info) #print('\ncontent:',content,'\n') index=content.find('Attached GPUs') s=content[index:].replace(' ','').rstrip('\n') self.t_send(s, toUserName='filehelper') time.sleep(.5) #th.exit() #============================================================================== # #==============================================================================
def add_event_detect(pin, value, callback, debouncingtime): iopath=get_gpio_path(pinname2kernelid(pin)) if os.path.exists(iopath): fd = open(iopath + '/value','w') fd.write(str(value)) else: return kernel_id=pinname2kernelid(pin) if fd!=None: set_edge(kernel_id,value) thread.start_new_thread(wait_edge,(fd,pin,callback,debouncingtime)) return else: thread.exit() fd.close() #End of RPi.GPIO wrapper functions
def fetch_meta(self, video): try: site = download_npo.match_site(video['url']) videourl, player_id, ext = site.find_video(video['url']) meta = site.meta(player_id) text = download_npo.make_filename(video['outdir'], video['filename'], 'mp4', meta, True, True, True) extra_text = ['{} kwaliteit'.format( ['hoge', 'middel', 'lage'][video['quality']])] if video['subtitles']: extra_text.append('ondertitels') if video['overwrite']: extra_text.append('overschrijven') text += ' ({})'.format(', '.join(extra_text)) except Exception as exc: video['status'] = 3 text = '{} - Fout'.format(video['url'], sys.exc_info()[1]) self.make_progress_frame_entry(text, video) thread.exit() # TODO: Voeg optie toe om te beperken tot /n/ processen
def timer(t, flag): global FLAG_COMPLETE global TIME_OVER_FLAG if (not flag): thread.exit() start = time.time() while(True): if(FLAG_COMPLETE): thread.exit() time.sleep(5) # print "#######\ntime.time() - start %f : t is %d" %(time.time() - # start,(int)(t)) if(time.time() - start > float(t)): print "****timer:time out!" # if(FLAG_COMPLETE): # thread.exit() TIME_OVER_FLAG = True thread.interrupt_main() #raise NameError("Time Out!") thread.exit()
def exit(code=0): preloader.stop() if threading.current_thread().__class__.__name__ == '_MainThread': sys.exit(code) else: thread.exit()
def GetUserAuthCode(): """Prompts the user for a two factor auth code.""" try: code = None if code is None: code = rawInput("Two-Factor Authentication Code: ") except (KeyboardInterrupt, SystemExit), e: if e.message: tools.exit(e.message) else: tools.exit return code
def printList(listItems, title="", showSelector=False, showByStep=20, showUrl=False): if title: separator("=", title) total = len(listItems) printLine("Total found: %d" % total) for key, item in enumerate(listItems): key += 1 printLine("%s : %s%s%s" % ( str(key).rjust(3, " "), printDate(item.created).ljust(18, " ") if hasattr(item, 'created') else '', item.title if hasattr(item, 'title') else item.name, " " + (">>> " + config.NOTE_URL % item.guid) if showUrl else '',)) if key % showByStep == 0 and key < total: printLine("-- More --", "\r") tools.getch() printLine(" " * 12, "\r") if showSelector: printLine(" 0 : -Cancel-") try: while True: num = rawInput(": ") if tools.checkIsInt(num) and 1 <= int(num) <= total: return listItems[int(num) - 1] if num == '0': exit(1) failureMessage('Incorrect number "%s", ' 'please try again:\n' % num) except (KeyboardInterrupt, SystemExit), e: if e.message: tools.exit(e.message) else: tools.exit
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 exit(): """Dummy implementation of thread.exit().""" raise SystemExit
def gpu_status(self,av_type_list): for t in av_type_list: cmd='nvidia-smi -q --display='+t #print('\nCMD:',cmd,'\n') r=os.popen(cmd) info=r.readlines() r.close() content = " ".join(info) #print('\ncontent:',content,'\n') index=content.find('Attached GPUs') s=content[index:].replace(' ','').rstrip('\n') self.t_send(s) time.sleep(.5) #th.exit()
def _on_keyboard(self, key, x, y): if key == 'q': self.stop_flag = True thread.exit() if key == 'f': if not self._in_fullscreen: self._orig_w = self.win_width self._orig_h = self.win_height glutFullScreen() self._in_fullscreen = True else: glutReshapeWindow(self._orig_w, self._orig_h) self._in_fullscreen = False if key in ('w', 's', 'a', 'd'): if time() - self.prev_move_time > self.move_accel_dt or \ key != self.prev_move_key: self.move_velo = 0 self.prev_move_time = time() self.prev_move_key = key self.move_velo += self.move_accel if key == 'w': self.camera.move_forawrd(self.move_velo) elif key == 's': self.camera.move_forawrd(-self.move_velo) elif key == 'a': self.camera.move_right(-self.move_velo) else: self.camera.move_right(self.move_velo)
def clientTearDown(self): self.done.set() thread.exit()
def retrieveThread(optDic, taskCtrl, dummy): """ """ info(4,"Entering retrieveThread(%s) ..." % getThreadName()) client = testClient().parseSrvList(optDic["servers"][NGAS_OPT_VAL]) while (1): nextFileId = taskCtrl.getNextFileId() if (not nextFileId): thread.exit() nextFileId = nextFileId[:-1] info(1,"Next File ID: %s" % nextFileId) try: fileSize, fileObj = client.retrieveFileObj(nextFileId) sizeRemain = fileSize while (sizeRemain): if (sizeRemain < BLOCK_SIZE): reqSize = sizeRemain else: reqSize = BLOCK_SIZE buf = fileObj.read(reqSize) sizeRemain -= len(buf) taskCtrl.incBytesRecv(fileSize) except Exception, e: error("Error retrieving file with ID: %s - skipping. Error: %s" %\ (nextFileId, str(e)))
def archiveThread(testObj, no, inc, dummy): """ Archive a file X times. testObj: Reference to instance of ngamsTestSuite object (ngamsTestSuite). no: Number allocated to thread (integer). inc: Increment ARCFILE keyword before submitting each Archive Request (0|1/integer). Returns: Void """ if (inc): filename = "tmp/ngamsArchiveStressTest_%d.fits" % no cpFile("src/TinyTestFile.fits", filename) incArcfile(filename, step=(100 * no)) else: filename = "src/TinyTestFile.fits" testStr = TST_STR1 % os.path.basename(filename) for n in range(5): if (not RUN_TEST): THREAD_STAT[no] = "STOPPED" break if (inc): incArcfile(filename) statObj = sendPclCmd(auth=AUTH).archive(filename) if (statObj.getMessage() != testStr): THREAD_STAT[no] = "FAILURE: Archive Request failed" THREAD_STAT[no] = "SUCCESS" thread.exit()
def cancel_transfer(self): if self.cancel_button["text"] == "Cancel": # If the cancel button says "Cancel" then we want to set the exit flag to True self._thread_should_exit = True elif self.cancel_button["text"] == "Clear": # Otherwise if the cancel button says "Clear" we have to remove the upload frame self.grid_forget()
def set_edge(self,value,callback,debouncingtime=0): if self.fd!=None: set_edge(self.kernel_id,value) thread.start_new_thread(self.wait_edge,(self.fd,callback,debouncingtime)) return else: thread.exit() return
def runWithAccident(): print "***ready to test with event" for (ip,name) in nodes: accidentJoin(ip) time.sleep(2) print "****all nodes restarted" #time.sleep(10) #print "****wait for key" #raw_input() interval=event_interval try: if(options.recur): simulateThread=threading.Thread(target=recurEventThread, args=(interval,test_time,)) else: simulateThread=threading.Thread(target=simulateAccidentThread, args=(interval,test_time,)) #simulateThread=threading.Thread(target=simulateAccidentThread,args=(interval,test_time)) #simulateThread.start() simulateThread.setDaemon(True) simulateThread.start() runTest() GLOBAL_FLAG=False print "****global flag:",GLOBAL_FLAG simulateThread.join() except KeyboardInterrupt: exit(-1)
def runWithUser(): global GLOBAL_FLAG global test_time #reset all flag and let nodes work for (ip,name) in nodes: resetFlag(ip) print "***ready to test with userdefine" #time.sleep(10) #print "****wait for key" #raw_input() interval=event_interval try: #if(1): #simulateUserThread(interval,test_time) #exit(0) if(options.recur): simulateThread=threading.Thread(target=recurUserThread, args=(interval,test_time,)) else: simulateThread=threading.Thread(target=simulateUserThread, args=(interval,test_time,)) #simulateThread=threading.Thread(target=simulateAccidentThread,args=(interval,test_time)) #simulateThread.start() simulateThread.setDaemon(True) simulateThread.start() runTest() GLOBAL_FLAG=False print "****global flag:",GLOBAL_FLAG simulateThread.join() except KeyboardInterrupt: for (ip,name) in nodes: resetFlag(ip) exit(-1) return
def handler(a,b): global GLOBAL_FLAG GLOBAL_FLAG=False exit(0)
def run(self): global options sleepTime = self.sleepTime slice = self.slice # print "****time limit:",slice, slice*2 while (1): startTime = self.startTime stopTime = time.time() totalTime = stopTime - startTime # print "in timerThread, total time now %f" %(totalTime) if (slice * 2 <= totalTime): print "****Error in spark:too long time!" thread.interrupt_main() exit(0) thread.exit() if (slice <= totalTime): print "****Timer:timeLock is locked!" # reset all flag # nodes=readConf() # for (ip,name) in nodes: # resetFlag(ip) break # print "****timer sleep" # print "****pass time:", totalTime time.sleep(sleepTime) global eventThread # eventThread.setRun(False) print "****Timer:total time:%f" % (totalTime) options.TIME_OUT_SIGNAL = True print "****Timer:time over trigger:", options.TIME_OUT_SIGNAL thread.interrupt_main()
def timer(startTime): global TIME_OUT_SIGNAL print ("in timerThread") sleepTime=10 slice=options.timelimit total=0 while (1): stopTime=time.time() totalTime=stopTime - startTime # print "in timerThread, total time now %f" %(total) if (slice * 2 <= totalTime): print "****Error in spark:too long time!" thread.interrupt_main() thread.exit() if (slice <= totalTime): print "timer:timeLock is locked!" break time.sleep(sleepTime) print "total time:%f" % (totalTime) TIME_OUT_SIGNAL=True # on_signal_usr1(0,0) # os.kill(pid,signal.SIGUSR1)