【发布时间】:2021-07-03 13:37:36
【问题描述】:
我写了一个小应用程序,它会抓取我学校的网站,然后查找最后一篇文章的标题,将其与旧标题进行比较,如果不一样,它会向我发送一封电子邮件。 为了让应用程序正常工作,它需要保持 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 保持此代码在主机上运行? 我知道我可以使用 cron 作业每隔 2 小时左右运行一次,但我不知道如何保持脚本本身运行,当我关闭应用程序终止的页面时使用终端不起作用
【问题讨论】:
-
你应该解释为什么你需要这方面的帮助;是什么阻止它按原样 24/7 运行?看起来它应该已经这样做了。它崩溃了吗?主机是否正在杀死进程?主机偶尔会重启吗?所有这些都可能有不同的解决方案,您可能需要多种解决方案,具体取决于问题所在。
-
这可能更多是操作系统或 Cpanel 的问题。如果你在 Cpanel 下运行 Linux 服务器,那么让 python 进程永久运行的一种方法是:nohup python yourcode.py > logfile & nohup 在你断开连接时保持进程运行,并且 & 在后台启动它,这样你可以注销。你在 Cpanel 上运行服务器吗??
-
您可以使用操作系统提供的调度程序,例如,通过 cron 运行您的脚本。
标签: python automation web-hosting smtplib