如何知道正在运行的脚本是否死掉?

发布于 2025-01-06 14:49:02 字数 340 浏览 1 评论 0原文

所以我对编程有点陌生,而且大部分是自学的,如果这个问题有点适合新手,我很抱歉。

我有一个长时间运行的 python 脚本(例如,它每隔几秒下载一次页面,连续几天)。类似于 Web 应用程序的监控脚本。

时不时地,某些东西会扰乱它,并且需要重新启动。我已经将这些事件降到了最低限度,但它仍然每隔几天就会发生一次,当它被杀死时,如果我几个小时没有注意到,那可能是个坏消息。

现在它正在 VPS 上的屏幕会话中运行。

有人可以为我指明正确的方向,了解脚本何时终止/并自动重新启动吗?

这是用 Bash 写的东西吗?或者其他什么?我以前从未做过类似的事情,不知道从哪里开始,甚至不知道寻找信息。

So I'm somewhat new to programming and mostly self-taught, so sorry if this question is a bit on the novice side.

I have a python script that runs over long periods (e.g. it downloads pages every few seconds for days at a time.) Sort of a monitoring script for a web app.

Every so often, something will disrupt it, and it'll need restarted. I've gotten these events to a bare minimum but it still happens every few days, and when it does get killed it could be bad news if I don't notice for a few hours.

Right now it's running in a screen session on a VPS.

Could someone point me in the right direction as far as knowing when the script dies / and having it automatically restart?

Would this be something to write in Bash? Or something else? I've never done anything like it before and don't know where to start or even look for information.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

最后的乘客 2025-01-13 14:49:02

你可以尝试supervisord,它是一个控制守护进程的工具。

You could try supervisord, it's a tool for controlling daemon processes.

亚希 2025-01-13 14:49:02

您应该对您的程序进行守护进程。

高效Python守护进程中所述,您可以安装并使用python-daemon 实现了 PEP 3143,“标准守护进程库”。

创建一个包含如下内容的文件 mydaemon.py

#!/usr/bin/env python

import daemon
import time
import logging

def do_something():
    name = 'mydaemon'
    logger = logging.getLogger(name)
    handler = logging.FileHandler('/tmp/%s.log' % (name))
    formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
    handler.setFormatter(formatter)
    logger.addHandler(handler) 
    logger.setLevel(logging.WARNING)

    while True:
        try:
            time.sleep(5)
            with open("/tmp/file-does-not-exist", "r") as f:
                f.write("The time is now " + time.ctime())
        except Exception, ex:
            logger.error(ex)

def run():
    with daemon.DaemonContext():
        do_something()

if __name__ == "__main__":
    run()

要实际运行它,请使用:

python mydaemon.py

这将在 DaemonContext 中生成 do_something(),然后脚本 mydaemon.py 将退出。您可以使用以下命令查看正在运行的守护进程:pgrep -fl mydaemon.py。这个简短的示例将简单地将错误记录到 /tmp/mydaemon.log 中的日志文件中。您需要手动终止守护进程,否则它将无限期地运行。

要运行您自己的程序,只需将 try 块的内容替换为对您的代码的调用即可。

You should daemonize your program.

As described in Efficient Python Daemon, you can install and use the python-daemon which implements the well-behaved daemon specification of PEP 3143, "Standard daemon process library".

Create a file mydaemon.py with contents like this:

#!/usr/bin/env python

import daemon
import time
import logging

def do_something():
    name = 'mydaemon'
    logger = logging.getLogger(name)
    handler = logging.FileHandler('/tmp/%s.log' % (name))
    formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
    handler.setFormatter(formatter)
    logger.addHandler(handler) 
    logger.setLevel(logging.WARNING)

    while True:
        try:
            time.sleep(5)
            with open("/tmp/file-does-not-exist", "r") as f:
                f.write("The time is now " + time.ctime())
        except Exception, ex:
            logger.error(ex)

def run():
    with daemon.DaemonContext():
        do_something()

if __name__ == "__main__":
    run()

To actually run it use:

python mydaemon.py

Which will spawn do_something() within the DaemonContext and then the script mydaemon.py will exit. You can see the running daemon with: pgrep -fl mydaemon.py. This short example will simply log errors to a log file in /tmp/mydaemon.log. You'll need to kill the daemon manually or it will run indefinitely.

To run your own program, just replace the contents of the try block with a call to your code.

以往的大感动 2025-01-13 14:49:02

我相信在循环内执行 python 脚本的包装 bash 脚本应该可以解决问题。

while true; do
    # Execute python script here
    echo "Web app monitoring script disrupted ... Restarting script."
done

希望这有帮助。

I believe a wrapper bash script that executes the python script inside a loop should do the trick.

while true; do
    # Execute python script here
    echo "Web app monitoring script disrupted ... Restarting script."
done

Hope this helps.

筑梦 2025-01-13 14:49:02

这取决于您想要防范的失败类型。如果只是脚本崩溃,最简单的方法是将 main 函数包装在 try/ except 中:

import logging as log

while True:
    try:
        main()
    except:
        log.exception("main() crashed")

如果某些东西正在杀死 Python 进程,那么在 shell 循环中运行它可能是最简单的:

while sleep 1; do python checker.py; done

如果它崩溃是因为机器坏了……好吧……Quis custodiet ipsos custodes?

但是,要直接回答您的问题:检查它是否从 shell 运行的绝对最简单的方法是 grep ps 的输出:

ps | grep "python checker.py" 2>&1 > /dev/null
running=$?

当然,这并不是万无一失的,但通常是这样够好了。

That depends on the kind of failure you want to guard against. If it's just the script crashing, the simplest thing to do would be to wrap your main function in a try/except:

import logging as log

while True:
    try:
        main()
    except:
        log.exception("main() crashed")

If something is killing the Python process, it might be simplest to run it in a shell loop:

while sleep 1; do python checker.py; done

And if it's crashing because the machine is going down… well… Quis custodiet ipsos custodes?

However, to answer your question directly: the absolute simplest way to check if it's running from the shell would be to grep the output of ps:

ps | grep "python checker.py" 2>&1 > /dev/null
running=$?

Of course, this isn't fool-proof, but it's generally Good Enough.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文