简体   繁体   English

在超时的子进程中运行 python 脚本

[英]Running a python script in a subprocess with timeout

Python newbie here. Python 新手在这里。 So I want to run a python script in a subprocess.所以我想在子进程中运行 python 脚本。 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.此外,脚本也有可能具有没有基本情况的递归 function。

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.无论如何,对于无限循环,如果进程运行时间超过 3 秒,我想终止进程,使其不会永远运行。

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: run.py文件的内容是:

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.现在,它似乎正在超时,但如果我尝试使用out,err = proc.communicate() ,那么服务器就会挂起。 And if I look at my activity monitor, i can see a python process using up around 99% of my CPU.如果我查看我的活动监视器,我可以看到一个 python 进程占用了我大约 99% 的 CPU。 Any ideas?有任何想法吗?

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.也许你可以在这里使用这个解决方案来获取所有 output 直到它完成/超时: https://stackoverflow.com/a/4418193/593045只需将超时轮询添加到循环中。

Infinite recursion I can only hope, there is a way to check stack size of Python somehow or similar.无限递归我只能希望,有一种方法可以以某种方式或类似的方式检查 Python 的堆栈大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM