0

I have some code running in python exec:

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

And this code which running in exec would be change, and may be running a long time.

Now I want to stop the code running in exec and not change the code in it.What can I do?

wsf1990
  • 195
  • 2
  • 12

1 Answers1

1

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.).

Ted Klein Bergman
  • 9,146
  • 4
  • 29
  • 50
  • Thanks,May be this is the only method I can try. You were right,I want to use exec to run user-defined input.I want to write a online python editor.Can you give me some advise to avoid malicious user? – wsf1990 Dec 16 '19 at 14:52
  • @wsf1990 That will require quite some work for it to be safe. First, you should make sure the code is executed as a user with limited permissions. This will help you restrict their access to system-wide files or execute programs that can harm your computer. So first you need to create such a user, and then programmatically downgrade them in python code ([example](https://stackoverflow.com/a/6037494/6486738)). Then you need to restrict the modules they can use (like `sys` and `os`) as these interact directly with your computer. I haven't done this, but I think it's connected with my first point – Ted Klein Bergman Dec 16 '19 at 15:13
  • @wsf1990 Or there might be some way to create a _sandbox environment_. I haven't done this either, but there might be some libraries/tutorials out there. – Ted Klein Bergman Dec 16 '19 at 15:14
  • Didn't read this article all the way through, but it seems to go over some interesting points and links to resources: https://wiki.python.org/moin/SandboxedPython – Ted Klein Bergman Dec 16 '19 at 15:16
  • Here's a good stackoverflow answer regarding python sandboxing: https://stackoverflow.com/a/3068475/6486738 – Ted Klein Bergman Dec 16 '19 at 15:19