1

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.

Jay Dangar
  • 3,271
  • 1
  • 16
  • 35

1 Answers1

0

You need exec code in another thread, so wait for timeout in main thread, if timeout just kill the thread. Because thread does not provide stop method, sys.exit to exit the process.

Maybe you can try exec code in another process, python also support multiprocessing, process can be killed easily.

refer other question:

simple demo code follows:

import os
import time
import threading
import sys

def thread1_run(code):
    os.environ["NLTK_DATA"] = f"{dirname(__file__)}/nltk_data"
    env = {}
    exec (code, env, env)

#   This is the code to run NLTK functions...
def mainNLTK(code):
    global thread1
    timeout = 30 # seconds
    thread1 = threading.Thread(target=thread1_run, args=(code, 30))
    thread1.start()
    thread1_start_time = time.time()

    while thread1.is_alive():
        # exec code thread is running timeout 30s
        if time.time() - thread1_start_time > 30:
            # thread does not provide stop method, so just exit to kill process
            sys.exit(-1)
        time.sleep(1)
icejoywoo
  • 151
  • 5