【问题标题】:prevent infinite looping in python inside exec防止exec内部python中的无限循环
【发布时间】: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


    【解决方案1】:

    你需要在另一个线程中执行代码,所以在主线程中等待超时,如果超时就杀死线程。由于线程没有提供停止方法,sys.exit 退出进程。

    也许你可以在另一个进程中尝试执行代码,python也支持多处理,进程很容易被杀死。

    参考其他问题:

    简单的演示代码如下:

    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)
    

    【讨论】:

      猜你喜欢
      • 2012-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-18
      • 1970-01-01
      • 2021-01-16
      • 1970-01-01
      相关资源
      最近更新 更多