【发布时间】:2021-05-26 10:40:32
【问题描述】:
我正在创建一个 python IDE,为此我需要使用 exec() 函数。如果一个人编写如下无限运行的代码:
while(True):
print("hi")
我尝试使用线程并运行一个计时器 30 秒并引发异常,但它会停止该特定线程而不是运行无限循环的代码。
import io,os,cv2,sys,time,threading,ctypes,inspect
import matplotlib.pyplot as plt
import PIL.Image as Image
import numpy as np
from os.path import dirname
thread1=None
def _async_raise(tid, exctype):
tid = ctypes.c_long(tid)
if not inspect.isclass(exctype):
exctype = type(exctype)
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
if res == 0:
raise ValueError("invalid thread id")
elif res != 1:
ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
raise SystemError("Timeout Exception")
def stop_thread(thread):
_async_raise(thread.ident, SystemExit)
def thread1_run(n):
time.sleep(n)
# This is the code to run NLTK functions...
def mainNLTK(code):
global thread1
thread1 = threading.Thread(target=thread1_run, args=(30,))
thread1.start()
os.environ["NLTK_DATA"] = f"{dirname(__file__)}/nltk_data"
env={}
exec(code,env,env)
我想在exec() 函数内运行代码指定时间。我也尝试过使用signal 包,但也没有用。
我想运行 exec() 函数运行 30 秒,如果它没有在时间范围内停止,我应该引发超时异常。
【问题讨论】:
标签: python multithreading infinite-loop