I am creating an python IDE and for that I need to work with exec()
function. If a person writes infinitely running code like following :
while(True):
print("hi")
I tried working with thread and run a timer for 30 seconds and raise exception, but it stops that particular thread and not the code running infinite loop.
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)
I want to run code for specified time inside exec()
function. I have tried using signal
package also but it also didn't work.
I want to run exec()
function to run for 30 seconds and if it doesn't stop within timeframe, I should raise timeout exception.