0

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!

2
Contributors
8
Replies
11
Views
6 Years
Discussion Span
Last Post by pyTony
0

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.

0

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?

0

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

Edited by layr: got bash and python mixed up.

0

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

Thank you! That was it.

Edited by layr: n/a

1

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 by layr: n/a

0

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 by pyTony: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.