如何使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中,或将其符号链接放置到特殊目录中,守护程序将在后台处理启动它的工作.您可以在Wikipedia上阅读更多.有很多不同的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方法(例如,一个库)以使其自身能够守护.是的,这将需要一个简单的事件循环(您的事件可能是计时器触发的,可能由睡眠功能提供).

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.

此外,如果您使用带有循环的守护进程并且发生崩溃,此后没有人会检查邮件(如答案).如果脚本是作为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.