我如何在主机上保持 python 应用程序 运行 24/7?

How can i keep a python app running 24/7 on host?

我写了一个mini-app,它抓取了我学校的网站然后寻找最后一个post的标题,将它与旧标题进行比较,如果不一样,它会发送给我一封电邮。 为了让应用程序正常工作,它需要保持 运行ning 24/7,以便 title 变量的值是正确的。 这是代码:

import requests
from bs4 import BeautifulSoup
import schedule, time
import sys
import smtplib


#Mailing Info

from_addr = ''
to_addrs = ['']

message = """From: sender
To: receiver
Subject: New Post

A new post has been published
visit the website to view it: 
"""


def send_mail(msg):
    try:
        s = smtplib.SMTP('localhost')
        s.login('email',
         'password')
         
        s.sendmail(from_addr, to_addrs, msg)
        s.quit()
    except smtplib.SMTPException as e:
        print(e)


#Scraping
URL = ''

title = 'Hello World'


def check():
    global title
    global message

    page = requests.get(URL)
    soup = BeautifulSoup(page.content, 'html.parser')

    main_section = soup.find('section', id='spacious_featured_posts_widget-2')
    first_div = main_section.find('div', class_='tg-one-half')

    current_title = first_div.find('h2', class_='entry-title').find('a')['title']

    if current_title != title:
        send_mail(message)
        title = current_title
    else:
        send_mail("Nothing New")


schedule.every(6).hours.do(check)

while True:
    schedule.run_pending()
    time.sleep(0.000001)

所以我的问题是如何使用 Cpanel 在主机上保留此代码 运行ning? 我知道我可以使用 cron 作业 运行 它每隔 2 小时左右,但我不知道如何保持脚本本身 运行ning,当我关闭时使用终端不起作用应用终止的页面

所以 - 通常 运行 程序需要被守护进程。使用 double-fork 和 set-sid 基本上与您的终端断开连接。话虽如此,我自己从来没有真正做过,因为它通常是 (a) 错误的解决方案,或者 (b) 它是 re-inventing 轮子 (https://github.com/thesharp/daemonize).

在这种情况下,我认为更好的做法是每 6 小时调用一次脚本,而不是让它在内部每 6 小时执行一次操作。让您的程序对重启具有弹性几乎是大多数系统保持可靠的方式,并将它们放在自动重启它们的 'cradle' 中。

对于您的情况,我建议将标题保存到文件中,并在调用脚本时读取和写入该文件。它会使您的脚本更简单、更健壮,并且您将使用 battle-hardened 工具来完成这项工作。

几年后,当您编写的代码需要在整个机器崩溃并被替换(6 小时内,安装完所有东西)后存活下来时,您可以使用某种外部形式的存储(例如数据库) 而不是文件,使您的系统更具弹性。