如何让 Python 脚本像 Linux 中的服务或守护进程一样运行 [英] How to make a Python script run like a service or daemon in Linux

查看:35
本文介绍了如何让 Python 脚本像 Linux 中的服务或守护进程一样运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个 Python 脚本,用于检查某个电子邮件地址并将新电子邮件传递给外部程序.我怎样才能让这个脚本 24/7 全天候执行,比如在 Linux 中将它变成守护程序或服务.我是否还需要一个永远不会在程序中结束的循环,还是可以通过多次重新执行代码来完成?

I have written a Python script that checks a certain e-mail address and passes new e-mails to an external program. How can I get this script to execute 24/7, such as turning it into daemon or service in Linux. Would I also need a loop that never ends in the program, or can it be done by just having the code re executed multiple times?

推荐答案

这里有两个选择.

  1. 进行适当的cron 作业,调用您的脚本.Cron 是 GNU/Linux 守护进程的通用名称,它根据您设置的时间表定期启动脚本.您将脚本添加到 crontab 或将它的符号链接放入一个特殊目录,守护进程会处理在后台启动它的工作.您可以在维基百科阅读更多.有多种不同的 cron 守护进程,但您的 GNU/Linux 系统应该已经安装了它.

  1. Make a proper cron job that calls your script. Cron is a common name for a GNU/Linux daemon that periodically launches scripts according to a schedule you set. You add your script into a crontab or place a symlink to it into a special directory and the daemon handles the job of launching it in the background. You can read more at Wikipedia. There is a variety of different cron daemons, but your GNU/Linux system should have it already installed.

使用某种 python 方法(例如一个库)让您的脚本能够自我守护.是的,它需要一个简单的事件循环(其中您的事件是定时器触发,可能由 sleep 函数提供).

Use some kind of python approach (a library, for example) for your script to be able to daemonize itself. Yes, it will require a simple event loop (where your events are timer triggering, possibly, provided by sleep function).

我不建议您选择 2.,因为实际上您会重复 cron 功能.Linux 系统范式是让多个简单的工具交互并解决您的问题.除非有其他原因需要创建守护程序(除了定期触发),否则请选择其他方法.

I wouldn't recommend you to choose 2., because you would be, in fact, repeating cron functionality. The Linux system paradigm is to let multiple simple tools interact and solve your problems. Unless there are additional reasons why you should make a daemon (in addition to trigger periodically), choose the other approach.

此外,如果您在循环中使用 daemonize 并且发生崩溃,则在此之后没有人会检查邮件(正如 Ivan Nevostruev 在对 这个 答案).而如果将脚本添加为 cron 作业,它只会再次触发.

Also, if you use daemonize with a loop and a crash happens, no one will check the mail after that (as pointed out by Ivan Nevostruev in comments to this answer). While if the script is added as a cron job, it will just trigger again.

这篇关于如何让 Python 脚本像 Linux 中的服务或守护进程一样运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆