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)
python类exit()的实例源码
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 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 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 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 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 _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 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 clientTearDown(self):
self.done.set()
thread.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 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