Trying to set a time out in python much like you would in ruby.
I have a link that when I click it opens a popup but I can not access it because it causes the script to freeze until I kill it. I have been trying for months to access this popup to no joy in ruby watir-webdriver.
I am trying to timeout the call to popup and then access the popup window.
#timeout(3)
try:
b.execute_script("javascript:openMdlWindow('InvestmentDetailOptions.aspx?IDAssetType=','620','600');if(window.document.RetValue == '2'){window.parent.LoadinIframe('InvestmentDetail.aspx?FromMenu=N&IDAssetType=','Investment Details > Full View','false');}")
except Exception, e:
print 'timeout!'
any help will be dearly appreciated.
Just try this:
from splinter import Browser
from selenium.common.exceptions import TimeoutException
b = Browser('firefox')
b.driver.set_page_load_timeout(1)
try:
b.visit('http://www.bbc.com')
except TimeoutException:
pass
print b.html
import signal
from time import sleep
class TimeoutException(Exception):
pass
def do_something_else():
time = 5
sleep(time)
return 'do_something_else has to run for %d seconds' % time
def handler(signum, frame):
raise TimeoutException
def do_something_with_timeout(callback, timeout=3):
signal.signal(signal.SIGALRM, handler)
signal.alarm(timeout)
try:
value = callback()
signal.alarm(0)
return value
except TimeoutException:
pass
signal.signal(signal.SIGALRM, signal.SIG_IGN)
return 'time out'
def main():
print 'hello'
print do_something_with_timeout(do_something_else)
print 'world'
main()
Related
Hello guys I have a problem with my kivy app when i start to run some functions the app stop responding i tried to solve it by using threading but its not working with.
so this is widget class :
class PyWidget(Widget):
stop = threading.Event()
def start_thread(self):
self.ids.mic.source = 'assets/open2.png'
self.ids.mic.reload()
time.sleep(1)
threading.Thread(target=self.start_listening).start();
#mainthread
def start_listening(self):
while True:
try:
time.sleep(1)
print('Listening.......')
voiceText = RecognizeVoice()
# time.sleep(1)
if 'hello' in voiceText and Talking(App, respone, RecognizeVoice):
return
# else: Talking(App, respone, RecognizeVoice)
time.sleep(1)
except Exception as e:
print(f'start_listening: {e}')
RecognizeVoice function to start the mic and get user voice to text
def RecognizeVoice():
try:
with speechRec.Microphone() as sound:
voice = recognizer.listen(sound)
voiceText = recognizer.recognize_google(voice, language="en-US") #online
voiceText = voiceText.lower()
print(f'Input : {voiceText}')
return voiceText
except speechRec.UnknownValueError as e:
print(f'RecognizeVoice: {e}')
except speechRec.RequestError as e:
print(f'RecognizeVoice: {e}')
respone('Sorry, something went wrong.')
# Text to speech
def respone(message):
AI.say(message)
AI.runAndWait()
in my GUI i have a button that when i click the start_thread function starts and all others follow it, i hope that i explained everything. thanks for helping
The #mainthread decorator on the start_listening() method defeats the threading. Just remove that decorator.
I want to check if a browser opened with Selenium is still open. I would need this check for closing a program. If the browser is not open, then the GUI should be destroyed without a message (tk.messagebox) coming. But if the browser is open, then the message should come as soon as the function is activated. Here is the function:
def close():
msg_box = tk.messagebox.askquestion('Exit Application', 'Are you sure you want to exit the application?',
icon='warning')
if msg_box == 'yes':
root.destroy()
try:
web.close()
except NameError:
sys.exit(1)
except InvalidSessionIdException:
sys.exit(1)
except WebDriverException:
sys.exit(1)
else:
return
I don't think there is a direct api for checking browser status. But you can use the the work around
def isBrowserAlive(driver):
try:
driver.current_url
# or driver.title
return True
except:
return False
Unfortunately, there's not a standardized way to check a driver's status.
Here's the most reliable cross-browser workaround that I've come up with over the years:
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import WebDriverException
def is_webdriver_alive(driver):
print('Checking whether the driver is alive')
try:
assert(driver.service.process.poll() == None) #Returns an int if dead and None if alive
driver.service.assert_process_still_running() #Throws a WebDriverException if dead
driver.find_element_by_tag_name('html') #Throws a NoSuchElementException if dead
print('The driver appears to be alive')
return True
except (NoSuchElementException, WebDriverException, AssertionError):
print('The driver appears to be dead')
return False
except Exception as ex:
print('Encountered an unexpected exception type ({}) while checking the driver status'.format(type(ex)))
return False
Usage:
driver_is_alive = is_webdriver_alive(driver)
I have the following code:
import click
#click.command()
def main():
while True:
pass
try:
main()
except KeyboardInterrupt:
print('My own message!')
When I press Ctrl+C to exit the program, I want to print my own message. However, click intercepts the error and this is the output:
^C
Aborted!
How can I stop click from handling the errors?
I think I've solved my problem with this code! Hopefully, it's the correct way to handle my problem.
import click
#click.command()
def main():
while True:
pass
try:
main(standalone_mode=False)
except click.exceptions.Abort:
print('My own message!')
I want to have a Python script running that looks for someone to interact with it in a specified time period (say, a week). If someone interacts with it, it continues to another loop of looking for an interaction. If someone does not interact with it, then it starts performing some actions.
I have started such a script using the module signal (and an example timeout of 20 seconds), but the timeout doesn't seem to be working; the script immediately launches into non-interaction actions. What is going wrong? Is there a better approach to this problem?
#!/usr/bin/env python
import propyte
import signal
import time
def main():
response = "yes"
while response == "yes":
response = get_input_nonblocking(
prompt = "ohai?",
timeout = 20 #604800 s (1 week)
)
print("start non-response procedures")
# do things
def alarm_handler(signum, frame):
raise Exception
def get_input_nonblocking(
prompt = "",
timeout = 20, # seconds
message_timeout = "prompt timeout"
):
signal.signal(signal.SIGALRM, alarm_handler)
signal.alarm(timeout)
try:
response = propyte.get_input(prompt)
signal.alarm(0)
return response
except Exception:
print(message_timeout)
signal.signal(signal.SIGALRM, signal.SIG_IGN)
return ""
if __name__ == '__main__':
main()
You can simply write:
import signal
TIMEOUT = 20 * 60 # secs to wait for interaction
def interrupted(signum, frame):
"called when read times out"
print('Exiting')
signal.signal(signal.SIGALRM, interrupted)
def i_input():
try:
print('You have 20 minutes to interact or this script will cease to execute')
foo = input()
return foo
except:
# timeout
return
# set alarm
signal.alarm(TIMEOUT)
inp = i_input()
# disable the alarm if not wanted any longer
# signal.alarm(0)
def signal_handler(signum, frame):
raise Exception("Timeout")
def my_function():
signal.signal(signal.SIGALRM, signal_handler)
signal.alarm(1)
try:
call_long_function()
except Exception as e: # Doesn't work
print("Hello, Timeout!")
break
signal.alarm(0)
How to correctly handle signal exception? Also I tried to handle Timeout exception, it doesn't work too.
It just prints "Error: Timeout" to the console and after it program will be closed.
Thanks in advance.
You're probably better off subclassing Exception into your own Exception class:
class TimeOutException(Exception):
def __init__(self, message, errors):
super(TimeOutException, self).__init__(message)
self.errors = errors
Then you can do:
def signal_handler(signum, frame):
raise TimeOutException("Timeout!")
Then, in the other function:
try:
call_long_function():
except TimeOutException:
print "Got a timeout!"
break
It is better to create a specific exception class for the timeout exception so you can differentiate between it and other exceptions.
class TimeoutException(Exception):
def __init__(self, *args, **kwargs):
pass
Define an alarm signal in your function, and set a timer.
Then wrap your time limited code with a try/except.
In this example i used two cases - one for the timeout exception class - one for any other sort of exception assuming the code can fail for more than one reason.
def my_function():
signal.signal(signal.SIGALRM, signal_handler)
signal.alarm(1) # Time Limit
try:
time.sleep(120) # Simulation of code exceeding time limit
except TimeoutException:
print "Time out"
except:
print "Some other exception"
def signal_handler(signum, frame):
raise TimeoutException()
try using the following snippet:
try:
//CODE
except Exception,e:
//handle the exception.
The whole point is not to use the expression Exception as e