Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
363 views
in Technique[技术] by (71.8m points)

Scheduling Python Script but just blinking

I am relatively new to python and i am experiencing some issues with schedule. I have a simple BeautifulSoup code which is parse some news title from 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' )

My codes working perfectly but i tried to add schedule to run every 5sec. (its just testing)

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)

In order to execute that py nothings happen and just blinking at shell. I dont have any outputerror log. Thats because i dont know what to do. How do I resolve this issue?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use cronTab for having an interval in executing your script:

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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...