【问题标题】:Scheduling Python Script but just blinking调度 Python 脚本但只是闪烁
【发布时间】:2021-04-10 02:35:21
【问题描述】:

我对 python 比较陌生,并且遇到了 schedule 的一些问题。我有一个简单的 BeautifulSoup 代码,它可以解析一些来自 usatoday 的新闻标题。

    class Command(BaseCommand):
    def handle(self,  *args, **options):
        html = urlopen('')
        soup = BeautifulSoup(html, 'html.parser')
        site_json=json.loads(soup.text)

   for i in range(len(site_json)):
                title = site_json[i]['title']

                try:
                    Job.objects.create(
                        title=title,)
                print('%s added' % (title,))
            except Exception as e: print(e)
            #   print('%s already exists' % (title,))
        self.stdout.write( 'job complete' )

我的代码运行良好,但我尝试添加计划以每 5 秒运行一次。 (它只是测试)

import time
import schedule
from os import system

def sch():
    class Command(BaseCommand):
        def handle(self,  *args, **options):
            html = urlopen('')
            soup = BeautifulSoup(html, 'html.parser')
            site_json=json.loads(soup.text)

   for i in range(len(site_json)):
                title = site_json[i]['title']

                try:
                    Job.objects.create(
                        title=title,)
                print('%s added' % (title,))
            except Exception as e: print(e)
            #   print('%s already exists' % (title,))
        self.stdout.write( 'job complete' )

schedule.every(5).seconds.do(sch)

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

为了执行 py,什么都没有发生,只是在 shell 处闪烁。我没有任何输出\错误日志。那是因为我不知道该怎么做。我该如何解决这个问题?

【问题讨论】:

  • 有必要使用Command 类吗?他们的方式你尝试使用时间表是正确的。也许尝试改用 crontab?

标签: python python-3.x function html-parsing


【解决方案1】:

您可以使用 cronTab 来设置执行脚本的时间间隔:

import getpass
from crontab import CronTab
 
cron = CronTab(user=getpass.getuser())
job = cron.new(command='python3 path/to/my/code.py')
job.second.every(5)
 
cron.write()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多