子进程无法成功重启目标python文件

时间:2015-02-03 15:03:50

标签: python windows subprocess restart

我编写了一个程序my_test.py来从web获取数据并存储到mysql。 但程序my_test.py崩溃了很多(我糟糕的编程技巧......),我试图监视它的状态并在崩溃时重新启动它。 我使用subprocess modular和以下代码。

import subprocess
import time
p = subprocess.Popen(['python.exe', r'D:\my_test.py'], shell=True)
while True:
    try:
        stopped = p.poll()
    except:
        stopped = True
    if stopped:
        p = subprocess.Popen(['python.exe', r'D:\my_test.py'], shell=True)
    time.sleep(60)

但是当my_test.py崩溃时,窗口警告窗口跳出来警告我my_test.py已关闭以及我将选择哪个操作:停止,调试...... 这样的事情。 my_test.py似乎被警报窗口冻结,上面的代码无法成功重启。 只有当我通过选择“关闭”手动关闭窗口时,它才会重新启动。

有没有解决此问题的方法,以便我的代码在发生故障时可以成功重启my_test.py

对不起因为我的英语不好而带来的不便,并提前感谢您的善意建议。

1 个答案:

答案 0 :(得分:0)

您的问题分为两部分:

如何重启

优先顺序:

  1. 修复my_test.py,以避免因已知问题而崩溃
  2. 使用主管程序来运行您的脚本,例如upstartsupervisord - 如果崩溃,他们可以自动重启
  3. 使用自己需要维护的错误编写自己的主管程序
  4. 如果您可以找到适用于Windows的已编写的主管程序(upstartsupervisord在Windows上不起作用),最好将自己限制在选项1和/或2中。< / p>

    您当前的主管脚本可以进行改进,以避免在重新启动程序之后等待一分钟,如果程序已经运行超过一分钟就会崩溃:

    #!/usr/bin/env python3
    import sys
    import subprocess
    import time
    try:
        from time import monotonic as timer
    except ImportError:
        from time import time as timer # time() can be set back
    
    while True:
        earliest_next_start = timer() + 60
        subprocess.call([sys.executable, r'D:\my_test.py'])
        while timer() < earliest_next_start:
            time.sleep(max(0, earliest_next_start - timer()))