Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to reexecute if an error occurs in python?

I’m working with Twint(a Twitter scraper) but somehow there is a problem that I can’t fix. I wonder if there is a way that when an error occurs, wait 1 min and re-execute this?
My code is like this:

import twint

geos = ["40.74566208501717, -73.99137569478954", "35.68802408270403, 139.76489869554837", "31.22521968438549, 121.51655148017774"]
    
for geo in geos:
    print(str(geo)+','+'10km')
    c = twint.Config()
    c.Limit = 20
    c.Geo = str(geo)+','+'10km'
    twint.run.Search(c)

Sometimes,twint.run.Search(c) can’t function correctly.So, once there is an error, is there a way to only execute this loop again but not re-executing the whole loop?

Would anyone help me? Any idea would be really helpful. Thank you much!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you want to simply pretend the error didn’t happen, you could do:

try:
    twint.run.Search(c)
except WhateverExceptionType:
    pass

(replace WhateverExceptionType with the actual type of error you’re seeing)

If when there’s an error you wanted to have the whole program wait for a minute before continuing the loop, put that in the except:

import time

...

    try:
        twint.run.Search(c)
    except WhateverExceptionType:
        time.sleep(60)

If you want it to re-execute that specific search after waiting (rather than continuing with the next loop iteration), put that in the except. Note that if code within an except raises, then it will raise out of the except and stop your program.

    try:
        twint.run.Search(c)
    except WhateverExceptionType:
        time.sleep(60)
        twint.run.Search(c)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading