When running the below code, if an error occurs or a connection times out, it triggers the loop so that the 'retrying code' is printed. But the code doesn't restart. It continuously prints 'retrying code' but that is all.
I wonder if it is anything to with the fact that the 'testingfile123.py' is working with http.requests?
import time
import os
os.system('python testingfile123.py')
while True:
try:
testingfile123.py()
print('running code')
except:
time.sleep(5)
print('retrying code')
Isn't this caused by the while True loop? Even if the code goes to the except section, it will just wait 5 seconds and print "retrying code". You would need some break statement.
Related
This script loops and even if it crashes it restarts.
Now I want it to restart the script even if it has NOT CRASHED yet.
while True:
try:
do_main_logic()
except:
pass
I have the loop that restart on crash, but I want it to restart on 60 seconds.
It is pretty hard to understand what you are asking for but i can still show how if works:
while True:
try:
#Try to do something
except:
#if it failed
else:
#if it succeded
You can do this :
from time import sleep
while True:
try:
do_main_logic()
except:
sleep(60)
pass
I am using selenium to scrape some data.
This is my code, simplified:
def get_usrs():
#DO SOMETHING
def scroll_down():
#SCROLL UNTIL ARRIVES TO THE BOTTOM OF THE PAGE
#CONTINUE WITH GET_USRS()
The problem is that when the code gets to scroll_down() it doesn't wait until it finishes but continues with get_usrs() and obviously encounters an error.
How can I solve this? Thanks in advance!
So, my code was running with:
try:
get_usrs()
except Exception as e:
print(e)
Now it's running with:
if __name__ == '__main__':
get_usrs()
Works fine.
Sorry I'm new to programming, and don't really understand how this Thread thing works. My goal was for this input to be timed, and I found some code that does that. However, I'm confused about the structure of this Thread because if you are "too slow", the program never continues on to print "checkpoint" as desired. It just sort of... freezes... Why is it getting stuck?
import time
from threading import Thread
answer = None
def check():
# waits for user input for 3 seconds
for i in range(3):
time.sleep(1)
if answer != None:
return
print('too slow')
Thread(target = check).start()
answer = input("Input something: ")
print('checkpoint')
One thing I tried is:
t = Thread(target = check)
t.start()
answer = input("Input something: ")
# also tried t.join()
if t.is_alive:
print('hi')
I tried to solve this program by trying to raise and catch an exception. However, I couldn't catch the exception. How do I catch it? (Or is there another solution to the problem I am having?)
import time
from threading import Thread
answer = None
def check():
# waits for user input for 3 seconds
for i in range(3):
time.sleep(1)
if answer != None:
return
print('too slow')
# was hoping to catch this as an exception
raise TimeoutError
# starts new thread
Thread(target = check).start()
# prompts user for an input
answer = input("Input something: ")
print('checkpoint')
What's good:
When you type something into the input prompt within 3 seconds, it prints "checkpoint" and continues on with code.
What's bad:
If you take "too long", the program prints "too slow!" as expected, BUT then it stops executing code and just sort of... freezes. So to try to fix this, I was hoping to raise a Timeout Error and then catch it, but I don't know how to catch it. This didn't catch the error:
try:
Thread(target = check).start()
except:
pass
This didn't either:
try:
answer = input("Input something: ")
except:
pass
Could I get some help? Thank you!
Edit: Forgot to mention that I am using linux so a lot of the solutions for my application did not work for me like msvcrt or keyboard. And modules that do work for Linux seem not to be "non-blocking."
You should think of the two threads as two separate programs, but sharing the same variables.
Thread 1 consists of everything that isn't indented in your code. It launches a thread, then it waits for user input, then it prints "checkpoint". Then it's done.
Thread 2 consists of the function check. It checks to see if the variable isn't None. If that happens it's done. If that doesn't happen in three seconds, it prints "too slow" and now it's done.
Neither thread "knows" what the other one is doing, except they share one variable, answer.
The program as a whole will exit when all its threads are finished.
That's it. That's what you've written. So if you type something, the program exits because Thread 1 will always exit after you type something. Thread 2 exits once it sees the variable isn't None.
If you don't type anything, Thread 1 will just sit there and wait for you, forever. That's how the input function works. Thread 2 will exit after 3 seconds or less, but that doesn't affect Thread 1.
You can't throw an Exception from one Thread to another. So you can't throw an exception from Thread 2 and have Thread 1 handle it.
Have you tried typing something AFTER the message "too slow" appears? When you do, Thread 1 (and therefore your program) will exit.
The bottom line is that you can't use the input function in cases like this, because that function blocks the flow of its thread until the user types something. There is nothing any other thread can do to make it continue.
DISCLAIMER: THIS DOESN'T ANSWER THE QUESTION BUT IN CASE YOU WANT TO KNOW HOW I GOT AROUND THE "INPUT" THING, HERE IS MY SOLUTION TO THE PROBLEM.
Actually I found something that works! It's a little strange but it works for what I am trying to do, thanks to #rayryeng 's answer here: detect key press in python?.
Problem Statement: Continue the program when 'enter' is pressed, and timeout if input takes too long. This does exactly that, although it displays strangely to the console... PS. I had to run this in my terminal as 'sudo' or it wouldn't work in my scratch file for whatever reason.
import curses
import os
from time import time, sleep
def main(win):
win.nodelay(True) # True turns on "non-blocking"
key=""
win.clear()
win.addstr("Please press 'Enter' to continue:")
start_time = time()
while 1:
end_time = time()
try:
if end_time-start_time > 5: # 5 seconds
return 'You are too slow!'
else:
key = win.getkey()
if key == os.linesep:
return 'OK. Continuing on...'
except Exception as e:
# No input
pass
p = curses.wrapper(main)
print(p) #-> either 'You are too slow!' or 'OK. Continuing on...'
I guess if you actually wanted to store the input you can modify it to be something like this:
def main(win):
win.nodelay(True) # True turns on "non-blocking"
key=""
win.clear()
win.addstr("Please press 'Enter' to continue:")
start_time = time()
while 1:
end_time = time()
try:
if end_time-start_time > 5: # 5 seconds
return 'You are too slow!'
else:
key = win.getkey() # gets a single char
if key: # == os.linesep:
return str(key) # returns that single char
except Exception as e:
# No input
pass
p = curses.wrapper(main)
print(p) #-> either 'You are too slow!' or character entered
And if you want to store more characters you could do something like this (just be aware that it also stores the "enter" key in the resulting string):
import curses
import os
from time import time, sleep
def main(win):
win.nodelay(True) # True turns on "non-blocking"
key=""
win.clear()
win.addstr("Please press 'Enter' to continue:")
start_time = time()
result = key # empty string
while 1:
end_time = time()
try:
if end_time-start_time > 5: # 5 seconds
return 'You are too slow!'
else:
key = win.getkey() # gets single char
result = result + str(key) # adds characters to the empty string
if key == os.linesep: # "new line"
return result
except Exception as e:
# No input
pass
p = curses.wrapper(main)
print(p) #-> either 'You are too slow!' or characters entered
This might be a simple situation that I expect many would have encountered it.
I have a simple python program that does something and sleeps for sometime in an infinite loop. I want to use signals to make this program exit gracefully on a SIGHUP. Now when a signal is sent to callee.py when it is in sleep, the program exits immediately whereas I expect it to finish the sleep and then exit.
Is there any workaround to bypass this behavior? I am also open to any other methods through which I can achieve this.
Note: This works as expected with python3 but I cannot port my existing module which is in python 2.7 to 3 now.
This is the code I have:
callee.py
stop_val = False
def should_stop(signal, frame):
print('received signal to exit')
global stop_val
stop_val = True
def main():
while not stop_val:
signal.signal(signal.SIGTERM, should_stop)
# do something here
print('Before sleep')
time.sleep(300)
print('after sleep')
caller.py
pid = xxx;
os.system('kill -15 %s' % pid)
I ran into the same issue today. Here is a simple wrapper that mimicks the python3 behaviour:
def uninterruptable_sleep(seconds):
end = time.time()+seconds
while True:
now = time.time() # we do this once to prevent race conditions
if now >= end:
break
time.sleep(end-now)
I'm trying to make alarm work over and over again.
My handler is
def handler_SIGALRM(signum, frame):
print "waiting"
signal.alarm(2)
The alarm work only once, even though every time I set it again.
In my code I also use sigchld and sys.exit after the child working.
I'm running it with cygwin.
EDIT:
I need to write a code that will print "waiting" every second, with sigalarm and not loops
I'm an idiot, I edited the wrong code
You put your signal.alarm(2) in a wrong place. See my example below.
import time
import signal
class TimeoutException (Exception):
pass
def signalHandler (signum, frame):
raise TimeoutException ()
timeout_duration = 5
signal.signal (signal.SIGALRM, signalHandler)
for i in range (5):
signal.alarm (timeout_duration)
try:
"""Do something that has a possibility of taking a lot of time
and exceed the timeout_duration"""
time.sleep (20)
except TimeoutException as exc:
print "Notify your program that the timeout_duration has passed"
finally:
#Clean out the alarm
signal.alarm (0)