Python: Looping check for internet - python

I'm coding a script that checks if there is any internet connection. I want it to print if there were any internet connection the last time it checked as well as if there is any currently.
def was_able_to_connect_to_internet():
try:
requests.get('https://google.com')
return True
except requests.exceptions.ConnectionError as e:
return False
was_able_to_connect_to_internet_last_time = was_able_to_connect_to_internet()
while True:
print(was_able_to_connect_to_internet_last_time, flush=True)
print(was_able_to_connect_to_internet(), flush=True)
print("-----", flush=True)
sleep(5)
I run the code and turn of the wifi when it has looped once and get the following output:
True
True
-----
True
False
-----
True
False
[Cancelled]
If it worked like I'd want it to the results would be the followning:
True
True
-----
True
False
-----
False
False
[Cancelled]
What changes should I make? All help is appreciated!

You forgot to update your was_able_to_connect_to_internet_last_time variable in the loop with the new value:
def was_able_to_connect_to_internet():
try:
requests.get('https://google.com')
return True
except requests.exceptions.ConnectionError as e:
return False
was_able_to_connect_to_internet_last_time = was_able_to_connect_to_internet()
while True:
print(was_able_to_connect_to_internet_last_time, flush=True) # Print previous status
was_able_to_connect_to_internet_last_time = was_able_to_connect_to_internet() # Update the "previous status variable with current status"
print(was_able_to_connect_to_internet_last_time, flush=True) # print current status using the previously updated variable to avoid pinging google twice
print("-----", flush=True)
sleep(5)

Related

Python try-except doesn't work as intended

I have the following code and for some reason it doesn't quit the browser when the two elif statements are triggered OR go to the except part of the code.
The goal is to return False in every case where the "Solved" attribute is not found. I have tried removing the elif parts so that it would go to except part in all of the other cases but it still doesn't work.
while True:
try:
sleep(10)
status = browser.find_element(By.CLASS_NAME, 'status')
if status.get_attribute("innerHTML") == "Solved":
break
elif status.get_attribute("innerHTML") == "Unknown error, watch console":
browser.quit()
print("Unknown error - programm ootab 3 minutit...\n")
sleep(180)
return False
elif status.get_attribute("innerHTML") == "Outdated, should be solved again":
browser.quit()
print("Captcha outdated - programm ootab 3 minutit...\n")
sleep(180)
return False
except:
print('Captcha fked up for some reason \n')
browser.quit()
return False

Python while wait 100 seconds and return True or False

I have python script below, which checks whether ping is success, If it success within 100 Seconds it will return True. If ping is failed it should return False but it is not returning False and when ping is success it is returning True.
Can anyone fix below code why it is not return False
Code:
def ping(self,hostname):
time_check = datetime.now()
data = ""
while not "Success" in data:
time.sleep(1)
data = self.pingCheck("ping 10.10.10.1 count 5")
if (datetime.now()-time_check).seconds > 100:
return False
return True
The code below will work for you:
import time
def ping(self, hostname, try_for=100):
t_end = time.time() + try_for
is_succeed = False
while time.time() < t_end or is_succeed:
time.sleep(1)
data = self.pingCheck("ping 10.10.10.1 count 5")
is_succeed = "Success" in data
return is_succeed
I've defined wait time as parameter called try_for, which default value is set to 100, but you can pass any other amount of seconds which you want spend waiting for host availability.

Python boolean value reset itself

I've got a small python script thats starts a movie and I can pause the movie by pressing a button. But I cannot play the movie again by pressing the same button.
I run it on a raspberry, so I listen to the GPIO pin.
import RPi.GPIO as GPIO
from omxplayer.player import OMXPlayer
from time import sleep
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(True)
GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP)
movie1 ='/home/pi/Downloads/big_buck_bunny_480p_surround-fix.avi'
status = None
def getButtonPress():
while 1:
if GPIO.input(18) == False:
return True
break
def statusMovie(status):
print('Status')
print(status)
print('after if:')
if status == True:
status = not status
print(status)
return status
else:
status = not status
print(status)
return status
def main():
print('begin main')
print(status)
try:
player = OMXPlayer(movie1)
while True:
if getButtonPress() == True:
if statusMovie(status) == True:
player.pause()
print('Stopping')
print(status)
print('end.....')
else:
player.play()
print('restarting movie')
print(status)
print('end.....')
sleep(2)
except KeyboardInterrupt:
print('Closing Player')
GPIO.cleanup()
if __name__ == "__main__":
if status is None:
status = False
main()
Well the movies starts playing, and I can pause the movie by pressing the button.
The problem is by my status boolean. I assign it at the start of running the script to False, Not sure if this is the right place to do it. Then I check and change it in the statesMovie(status) function.
I also change the boolean there so when I press the button again it can not only pause the movie.. But also play the movie again.
I dont know how but then the stateMovie(status) function return the value it change the value always to False back in the main function.
I got an output of the print's from the script:
begin main
False
Status
False
after if:
True <<<< Well here the boolean is correct!
Stopping
False <<<< But why is it False again!?
end.....
I will just talk about what you ask:
The problem is that you are modifying a local variable but won't reflect to outside variable.
You pass status to statusMovie and want to toggle it from True to False or from False to True. But actually, you just toggle the local status but not the outside status. if you want to toggle the outside status, you need to update it explicitly by status = statusMovie(status)

Python: run "try" again after exception caught and worked out

Is there any way to enter try statement once again after catching the exception in the first try?
Now I'm using "while" and "if" statements and it is making the code messy.
Any ideas?
Will try to simplify it as possible, sorry that have no logic...
run = True
tryAgain = True
a=0
while run:
try:
2/a
except Exception:
if tryAgain:
tryAgain = False
a = 1
else:
run = False
You could try using a break statement in your try block:
while True:
try:
# try code
break # quit the loop if successful
except:
# error handling
Considering you are doing this in a while, then you can make use of continue to just continue back to the beginning of the while loop:
tryAgain = True
a=0
while True:
try:
2/a
break # if it worked then just break out of the loop
except Exception:
if tryAgain:
continue
else:
# whatever extra logic you nee to do here
I like using a for loop so that the trying and trying doesn't go on forever. Then the loop's else clause is a place to put the "I give up" code. Here is a general form that will support 'n' retries > 1:
a=0
num_tries = 5
for try_ in range(0,num_tries):
try:
2/a
except Exception:
print("failed, but we can try %d more time(s)" % (num_tries - try_ - 1))
if try_ == num_tries-2:
a = 1
else:
print("YESS!!! Success...")
break
else:
# if we got here, then never reached 'break' statement
print("tried and tried, but never succeeded")
prints:
failed, but we can try 4 more time(s)
failed, but we can try 3 more time(s)
failed, but we can try 2 more time(s)
failed, but we can try 1 more time(s)
YESS!!! Success...
I'm new to Python, so this may not be best practice. I returned to the try statement after triggering the exception by lumping everything into a single function, then recalling that function in the except statement.
def attempts():
while True:
try:
some code
break #breaks the loop when sucessful
except ValueError:
attempts() #recalls this function, starting back at the try statement
break
attempts()
Hope this addresses your question.

Automatically restart program when error occur

The program is like this:
HEADER CODE
urllib2.initialization()
try:
while True:
urllib2.read(somebytes)
urllib2.read(somebytes)
urllib2.read(somebytes)
...
except Exception, e:
print e
FOOTER CODE
My question is when error occurs (timeout, connection reset by peer, etc), how to restart from urllib2.initialization() instead of existing main program and restarting from HEADER CODE again?
You could wrap your code in a "while not done" loop:
#!/usr/bin/env python
HEADER CODE
done=False
while not done:
try:
urllib2.initialization()
while True:
# I assume you have code to break out of this loop
urllib2.read(somebytes)
urllib2.read(somebytes)
urllib2.read(somebytes)
...
except Exception, e: # Try to be more specific about the execeptions
# you wish to catch here
print e
else:
# This block is only executed if the try-block executes without
# raising an exception
done=True
FOOTER CODE
How about just wrap it in another loop?
HEADER CODE
restart = True
while restart == True:
urllib2.initialization()
try:
while True:
restart = False
urllib2.read(somebytes)
urllib2.read(somebytes)
urllib2.read(somebytes)
...
except Exception, e:
restart = True
print e
FOOTER CODE
Simple way with attempts restrictions
HEADER CODE
attempts = 5
for attempt in xrange(attempts):
urllib2.initialization()
try:
while True:
urllib2.read(somebytes)
urllib2.read(somebytes)
urllib2.read(somebytes)
...
except Exception, e:
print e
else:
break
FOOTER CODE

Categories