在python脚本中调用IPython.embed()
时有没有办法超时?假设我有一个脚本在各个地方停留IPython.embed()
,当用户没有及时回复时,如何让脚本继续其业务?
答案 0 :(得分:1)
这不是问题的答案,但它足以满足我的需求。
我使用了
中的一些跨平台按键超时代码让用户在时间窗口内决定是否应该调用IPython.embed():
import time
import IPython
try:
from msvcrt import kbhit
except ImportError:
import termios, fcntl, sys, os
def kbfunc():
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:
while True:
try:
c = sys.stdin.read(1)
return c.decode()
except IOError:
return False
finally:
termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
else:
import msvcrt
def kbfunc():
#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:
return False
def wait_for_interrupt(waitstr=None, exitstr=None, countdown=True, delay=3):
if waitstr is not None: print(waitstr)
for i in range(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 is not None: print(exitstr)
return False
if __name__ == "__main__":
#wait_for_interrupt example test
if 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 loop
while True:
#acquire the keyboard hit if exists
x = kbfunc()
#if we got a keyboard hit
if x != False and x == 'i':
#we got the key!
IPython.embed()
#break loop
break
else:
#prints the number
print(number)
#increment, there's no ++ in python
number += 1
#wait half a second
time.sleep(0.5)