如何向exec发送停止信号

How to send stop signal to exec

我在 python exec:

中有一些代码 运行
# some code before exec
exec("""
# some code in exec
""")
# some code after exec

exec中运行的这段代码会被修改,可能会运行很久。

现在我想停止 exec 中的代码 运行 并且不更改 it.What 中的代码,我可以这样做吗?

您可以创建一个执行代码的新进程。进程异步执行,可以安全终止。

import multiprocessing 


def do_stuff(code): 
    print('Execution started')
    exec(code) 
    print('Execution stopped')


def main():
    process = multiprocessing.Process(target=do_stuff, args=("while True: pass", ))
    process.start()
    while process.is_alive():
        if input('Kill process? ') == 'yes':
            process.kill()


if __name__ == '__main__':
    main()

kill进程需要一些时间,所以这个例子在你输入yes后会再问一次'Kill process?',但是原理应该很清楚.

我要补充一点,您不应将 exec 与用户定义的输入一起使用。如果您知道在 exec 中执行了哪些代码,那很好。否则,您真的应该寻找其他替代方案,因为恶意用户可以执行对您的计算机造成巨大损害的代码(如删除文件、执行病毒等)。