Hi, i need a simple python code which would trigger a command if there is an internet connection; if there isn't, sleep for some time and check again until there is.
I found few examples, but they're all rather difficult to grasp and being new to python, I can't get them working. If there really is no simple solution for this in Python, i'll try and go with the other ones. Thanks!

I would just try to open any sure to be up url in try statement inside while True loop. In else statement of try I would put activity for internet open. Most likely a function call.

Ok, i've managed to get this far:

#!/usr/bin/env python2
import urllib2 
import time

f = open("/home/laur/.conky/data_file.dat", "w")
loop_value = 1

while (loop_value = 1):
try:
        urllib2.urlopen("http://google.com")
except urllib2.URLError, e:
	f.write( "Network currently down." )
	time.sleep( 5 )
else:
	f.write( "Up and running." )
	loop_value = 0

Other commads to run placed here.

Yet i get an error:

while (loop_value = 1):
                      ^
SyntaxError: invalid syntax

Is the 'loop_value' incorrectly defined?

Any hints perhaps?:D
Can't get any methods error-free nor working.

Edited 5 Years Ago by layr: got bash and python mixed up.

That is not Python, it is shell script.
You must use comparision operator ==

Thank you! That was it.

Edited 5 Years Ago by layr: n/a

For future searchers:

#!/usr/bin/python
import urllib2 
import time

loop_value = 1

while (loop_value == 1):
    try:
	urllib2.urlopen("http://www.google.com")
    except urllib2.URLError, e:
	time.sleep( 10 )
    else:
	loop_value = 0
	<commands to be ran when internet connection is established go here>

Edited 5 Years Ago by layr: n/a

Little docstring would be nice to catch the logic easier, like: """ Wait for connection to Internet to be established and do commands, then exit """. Good effort even my version would drop the flag variable and instead use break from end of else branch and while True: loop. I would not also put ', e' in except line as e is not used, also modern syntax is 'as e'

Edited 5 Years Ago by pyTony: n/a

This article has been dead for over six months. Start a new discussion instead.