You could create a new process that executes the code. Processes are executed asynchronously and can safely be terminated.
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()
It takes some time to kill the process, so this example will ask 'Kill process?' one time again after you've typed yes, but the principle should be clear.
I should add that you shouldn't use exec
with user-defined input. If you know what code gets executed in exec
, then it's fine. Otherwise, you should really look for other alternatives as a malicious user can execute code that does great damage on your computer (like delete files, execute viruses, etc.).