如何向执行器发送停止信号

时间:2019-12-16 11:41:09

标签: python exec

我在python exec中运行了一些代码:

# some code before exec
exec("""
# some code in exec
""")
# some code after exec

exec中运行的这段代码将被更改,并且可能运行很长时间。

现在我想停止在exec中运行的代码,而不要更改其中的代码。我该怎么办?

1 个答案:

答案 0 :(得分:1)

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

_grokparsefailure

消灭该过程需要花费一些时间,因此本示例将在您键入“是”后再次询问“杀死过程?” ,但原理应明确。

我还要补充一点,您不应将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() 与用户定义的输入一起使用。如果您知道在exec中执行了什么代码,那很好。否则,您应该真正寻找其他替代方案,因为恶意用户可以执行会对您的计算机造成极大损害的代码(例如删除文件,执行病毒等)。