正在安排 Python 脚本但只是闪烁

Scheduling Python Script but just blinking

我是 python 的新手,我在 日程安排 方面遇到了一些问题。我有一个简单的 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 处闪烁。我没有任何 output\error 日志。那是因为我不知道该怎么办。我该如何解决这个问题?

您可以使用 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()