2

Python newbie here. So I want to run a python script in a subprocess. So far, I'm able to do it and everything works as expected. However, there is a chance that the script can contain an infinite loop, so the subprocess would take forever to run. Furthermore, there is also a chance that script could have a recursive function with no base case.

The infinite loop might be easy to solve, although I'm not entirely sure how to solve the endless recursion problem. If you have any ideas, i'd love to hear them. Anyway, with the infinite loop, if the process is running longer than say, 3 seconds, I would like to kill the process so that it doesn't run forever.

Here is my code:

kill = lambda process: process.kill()
cmd = ["python", f"{settings.BASE_DIR}/api/scripts/run.py"]
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
my_timer = Timer(5, kill, [proc])

and the contents of the run.py file is:

def solution(name):
    while(True):
        print(name)
    
solution("joe")

I got the timeout code from this blog article.

ideally, it would be nice if I could receive the output/error if the process doesn't time out, but if for whatever reason it does timeout, then I would like to know that it did.

Right now, it appears to be timing out but if i try using out,err = proc.communicate(), then the server just hangs. And if I look at my activity monitor, i can see a python process using up around 99% of my CPU. Any ideas?

Angel Garcia
  • 1,547
  • 1
  • 16
  • 37

1 Answers1

0

Perhaps you can use this solution here to get all the output until it finishes/timeouts: https://stackoverflow.com/a/4418193/593045 Just add your timeout poll into the loop.

Infinite recursion I can only hope, there is a way to check stack size of Python somehow or similar.

BitLauncher
  • 587
  • 4
  • 15