Skip to content Skip to sidebar Skip to footer

Python: Network Calls Before Network Service Is Up

I have a script that gets launched on boot, and it is possible that it would be launched before networking is fully up. The following code fails if it is run before networking is u

Solution 1:

use requests and check the status code?

import requests
In [36]: r = requests.get('http://httpbin.org/get')

In [37]: r.status_code == requests.codes.ok
Out[37]: True

In [38]: r.status_code
Out[38]: 200200
In [33]:  r = requests.get('http://httpbin.org/bad')

In [34]: r.status_code
Out[34]: 404

In [35]: r.status_code == requests.codes.ok
Out[35]: Falsedefisup():
    try:
        r = requests.get(self.URL)
        return r.status_code == requests.codes.ok
    except Exception, e:
        print e
        returnFalse

Solution 2:

You could do it as:

defisup():
  try:
    urllib2.urlopen(self.URL).close()
    returnTrueexcept urllib2.URLError,e:
    passreturnFalse## Try the lookupwhilenot isup():
    pass#or replace pass with time.sleep(1) or time.sleep(0.5)
check()

Solution 3:

Why do you not use ping?

def isUp():
    ret = os.system("ping -c 1 www.google.com")
    return (ret != 0)

NOTE: this does not work on Windows as is but you got the idea...

Post a Comment for "Python: Network Calls Before Network Service Is Up"