Timeout When Invoking Ipython Embed()
Is there a way to have a timeout when calling IPython.embed() in a python script? Say I have a script that stops for a IPython.embed() at various places, how can I let the script g
Solution 1:
This is not quite an answer to the question, but it is adequate for what I wanted.
I used some cross-platform keypress timeout code from
to let the user decide within a time window if a IPython.embed() should be called:
import time
import IPython
try:
from msvcrt import kbhit
except ImportError:
import termios, fcntl, sys, os
defkbfunc():
fd = sys.stdin.fileno()
oldterm = termios.tcgetattr(fd)
newattr = termios.tcgetattr(fd)
newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
termios.tcsetattr(fd, termios.TCSANOW, newattr)
oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)
try:
whileTrue:
try:
c = sys.stdin.read(1)
return c.decode()
except IOError:
returnFalsefinally:
termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
else:
import msvcrt
defkbfunc():
#this is boolean for whether the keyboard has bene hit
x = msvcrt.kbhit()
if x:
#getch acquires the character encoded in binary ASCII
ret = msvcrt.getch()
return ret.decode()
else:
returnFalsedefwait_for_interrupt(waitstr=None, exitstr=None, countdown=True, delay=3):
if waitstr isnotNone: print(waitstr)
for i inrange(delay*10):
if countdown and i%10 ==0 : print('%d'%(i/10 + 1), end='')
elif countdown and (i+1)%10 ==0: print('.')
elif countdown : print('.', end='')
key = kbfunc()
if key: return key
time.sleep(0.1)
if exitstr isnotNone: print(exitstr)
returnFalseif __name__ == "__main__":
#wait_for_interrupt example testif wait_for_interrupt('wait_for_interrupt() Enter something in the next 3 seconds', '... Sorry too late'):
IPython.embed()
#begin the counter
number = 1#interrupt a loopwhileTrue:
#acquire the keyboard hit if exists
x = kbfunc()
#if we got a keyboard hitif x != Falseand x == 'i':
#we got the key!
IPython.embed()
#break loopbreakelse:
#prints the numberprint(number)
#increment, there's no ++ in python
number += 1#wait half a second
time.sleep(0.5)
Post a Comment for "Timeout When Invoking Ipython Embed()"