Gregory
Gregory

Reputation: 9

Restart python script if internet goes down

I have a python script (running on Mac OS X) that needs to be restarted when the internet goes down. If the internet is down, I would like to kill the current script, wait for the internet to go back up, and then restart it. Or, if possible, restart the function from within.

The problematic section of the Python code is as follows:

    import tweetstream

    # ...

    with tweetstream.FilterStream(username, password, track = words) as stream:
        for tweet in stream:
            db.tweets.save(tweet)

Currently, if the internet goes down, the stream stops and doesn't reconnect.

Upvotes: 0

Views: 1879

Answers (3)

tarashish
tarashish

Reputation: 1965

Perhaps you could try something like this:

import urllib2

def internet_on():
    try:
        response=urllib2.urlopen('http://74.125.131.94/',timeout=1)
        return True
    except urllib2.URLError as err: pass
    return False

74.125.131.94 is the ip address of google.co.in . You can use whatever site you think will respond more quickly. Using a numerical IP-address avoids a DNS lookup, which may block the urllib2.urlopen call.The timeout=1 parameter makes sure that the call to urlopen will not take longer than 1 second even if the internet is not available.

Now you just need to call the internet_on() function. It will return true if the connection is on, else return false. Then you might want to wrap all the tweeting code inside a function and call it. (As @inspectorG4dget suggested).

EDIT: For continuous checking you could do something like

def check():
    while not internet_on():
        pass
    print "internet connection is on"
    // call the tweet stuff function here.

Then when your stream stops just call the check() function and when the internet connection is back , it will call your tweet function to restart it.

Upvotes: 0

inspectorG4dget
inspectorG4dget

Reputation: 113915

Try using this python implementation of ping as a subprocess. Thus, if too many timeouts occur, then you'll know the network's down and you can re-initiate the tweet process (however, to do this, you should probably put the entire tweeting process in a function of its own)

Upvotes: 1

Dmitry Zagorulkin
Dmitry Zagorulkin

Reputation: 8548

It depends from os. There are few os specific methods. First cross platform method will be own ping which will be send some packets to the Internet server. If you can not receive info that means Internet is goes down.

Upvotes: 1

Related Questions