如何保持python脚本无限期地运行



我用python从Tkinter制作了一个GUI应用程序,并希望在特定时间后程序再次运行并相应地打印。

def check_price():
name = entry_1.get()
p = entry_2.get()
ex_price = float(p)
usr_email = entry_3.get()
client_response = Client(name)
source = client_response.html
soup = BeautifulSoup(source, 'html.parser')
try:
title=soup.find('span', id ='productTitle').get_text().strip()
label_4 = Label(root, text=title)
label_4.grid(row=4, column=0)
except AttributeError:
title = "Wrong URL"
label_4 = Label(root, text=title)
label_4.grid(row=4, column=0)
exit()
try:
price = soup.find('span', id ='priceblock_dealprice').get_text().strip()
x="The item is currently discounted at : "+price
label_5 = Label(root, text=x)
label_5.grid(row=5, column=0)
except AttributeError:
try:
price = soup.find('span', id ='priceblock_ourprice').get_text().strip()
x = "The product is not discounted currently and Currently the price is : "+price
label_5 = Label(root, text=x)
label_5.grid(row=5, column=0)
except AttributeError:
x = "Product Unavailable!!"
label_5 = Label(root, text=x)
label_5.grid(row=5, column=0)
exit()
px = ""
for ch in price:
if(ch.isdigit()):
px=px+ch
converted_price=float(px)
converted_price=converted_price/100
if(converted_price < ex_price):
send_mail(name, usr_email)
else: 
x = "The price is not currently below the price at which you would like to buy"
label_6 = Label(root, text=x)
label_6.grid(row=6, column=0)
self.after(10, self.check_price)

所以我希望check_price 1 小时后再次调用该函数,我该怎么做? 我使用了self.after,但它不起作用。

您可以使用 time.sleep 在一个无限循环中,睡眠时间为一小时,也可以使用调度库,如 sched,schedule。

使用 while 循环并执行它是一个后台进程。

文件名: check_price.py

while True:
check_price()
time.sleep(10)

将其作为后台进程运行。

Nohup Python check_price.py &

如果你真的想这样做,你必须使用 while 循环,如下所示:

import time
while True:
# Here goes some additional code if needed
check_prices()
time.sleep(60 * 60) #  Time to sleep process / thread in seconds

或者,我建议在操作系统级别启动程序,例如在Linux下使用cronjob

查看日程安排库。 您必须pip install schedule

才能使用它。
import schedule
schedule.every().hour.do(check_price)

最新更新