Need to rerun script after error or exception is risen - python

Need to rerun my selenium python script after either a 'list index is out of range' error or the page does not load and throughs some error or exception that has to due with it timing out. And no, upping the time for the page to load does not help, since it will continuously try to load. So is there a way to make the script stop and restart on its own if it encounters a problem?

Like this?
while True:
try:
<your script>
except <error>:
pass
else:
break

#kevin You are right. But this question needs little more.
def initiate_test_condition():
"""
This should have the initial setup (Environment where your testcase to be tested)
Example:
* reopening your browser and
* kill all already opened browsers
"""
pass
def test_case_flow():
"""
write your selenium testing code
"""
initiate_test_condition()
try:
"""
your testing code
"""
# if all code runs successfully
return 1
except Exception as error:
print str(error)
return 0
if __name__ == '__main__':
total_rerun = 0
while True:
if total_rerun != 5 and total_rerun < 5:
if test_case_flow():
print "Looks like the code is passed :)"
return or break
else:
total_rerun += 1
print "Rerunning the code"
else:
print "Code Failed after rerunning %d times " % total_rerun
break

Related

How to make this script loop until there are no errors python?

I'm trying to make this script loop until there are no errors but I'm pretty new to python and just keep encountering errors
I've tried everything I know but this isnt an easy task for me
def change_screen_name(self):
print("Attempting change...")
try:
status = self.api.update_profile(screen_name="name")
print("Name updated!")
except tweepy.TweepError as error:
resp = error.response.json()["errors"][0]
print("Name unavailable.")
print("{} ({})".format(resp["message"], resp["code"]))
finally:
return self
Expected result is to continue attempting the same namechange until there are no errors but it currently only tries once then stops
def change_screen_name(self):
while True:
print("Attempting change...")
try:
status = self.api.update_profile(screen_name="name")
print("Name updated!")
return self
except tweepy.TweepError as error:
resp = error.response.json()["errors"][0]
print("Name unavailable.")
print("{} ({})".format(resp["message"], resp["code"]))
1) Have an infinite loop running
2) Break out the infinite loop once your attempt succeeds.
3) Finally runs after try/except. If you have a finally statement it will always run.

Looping a Function In Python

I have a Function used against multiple devices listed in a LIST. It throws the error if it doesn't work against a particular devices and the script breaks.
def macGrabber(child,switch,cat = False):
try:
if cat is False:
child.expect('.#')
child.sendline('sh mac address-table | no-more')
else:
child.sendline('sh mac address-table dynamic | i Gi')
child.expect('.#', timeout=3000)
except pexpect.TIMEOUT:
print child.before,child.after
child.close()
raise
macs = child.before
child.close()
macs = macs.splitlines()
print('Connection to %s CLOSED' % switch)
return macs
Can we loop it ( retry multiple times ) before it goes to "Except' ? OR
Can we skip it and try for next device if it fails ?
You need to call macGrabber inside a try...except block and call continue if you would like to continue looping without the program crashing.
multiple_devices = [
(child1, switch1, cat1),
(child2, switch2, cat2),
...,
]
for device in multiple_devices:
try:
macGrabber(*device)
except pexpect.TIMEOUT as e:
print(f'{device} timed out')
print(e)
continue # <--- Keep going!
For the first question, yes, you can retry multiple times. Keep an error counter, wrap the whole try/except in a loop, and when you get an exception check the error counter and keep looping if it's less than (say) 5, otherwise raise the error as you're already doing.
error_count = 0
while True:
try:
if cat is False:
child.expect('.#')
child.sendline('sh mac address-table | no-more')
else:
child.sendline('sh mac address-table dynamic | i Gi')
child.expect('.#', timeout=3000)
break
except pexpect.TIMEOUT:
++error_count
if error_count < 5:
continue
print child.before,child.after
child.close()
raise
For the second question, yes, you can skip the device if it fails by just putting return None in the except handling. But you also would need to adjust the calling code to properly handle a None result.

Can not get keyboardInterrupt to catch ctrl c in python program running in linux

I want my program to stop executing when a ctrl-c is entered in the terminal window (that has focus) where the program is executing. Every google hit tells me this should work but it doesn't.
First I tried putting the try block in a class method my main invoked:
try:
for row in csvInput:
<process the current row...>
except KeyboardInterrupt:
print '\nTerminating program!\n'
exit()
and then I tried putting the try block in my main program and that didn't work:
if __name__ == '__main__':
try:
programArg = ProgramArgs(argparse.ArgumentParser)
args = programArg.processArgs()
currentDir = os.getcwd()
product = Product(currentDir, args.directory[0], programArg.outputDir)
product.verify()
except KeyboardInterrupt:
print '\nTerminating program!\n'
exit()
I recently (May 2, 2020) hit this same issue in Windows-10 using Anaconda2-Spyder(Python2.7). I am new to using Spyder. I tried multiple ways to get [break] or [ctrl-c] to work as expected by trying several suggestions listed in stackoverflow. Nothing seemed to work. However, what I eventually noticed is that the program stops on the line found after the "KeyboardInterrupt" catch.
[Solution]: select [Run current line] or [continue execution] from the debugger tools (either menu item or icon functions) and the rest of the program executes and the program properly exits. I built the following to experiment with keyboard input.
def Test(a=0,b=0):
#Simple program to test Try/Catch or in Python try/except.
#[break] using [Ctrl-C] seemed to hang the machine.
#Yes, upon [Ctrl-C] the program stopped accepting User #
Inputs but execution was still "hung".
def Add(x,y):
result = x+y
return result
def getValue(x,label="first"):
while not x:
try:
x=input("Enter {} value:".format(label))
x = float(x)
continue
except KeyboardInterrupt:
print("\n\nUser initiated [Break] detected." +
"Stopping Program now....")
#use the following without <import sys>
raise SystemExit
#otherwise, the following requires <import sys>
#sys.exit("User Initiated [Break]!")
except Exception:
x=""
print("Invalid entry, please retry using a " +
"numeric entry value (real or integer #)")
continue
return x
print ("I am an adding machine program.\n" +
"Just feed me two numbers using "Test(x,y) format\n" +
"to add x and y. Invalid entries will cause a \n" +
"prompt for User entries from the keyboard.")
if not a:
a = getValue(a,"first")
if not b:
b = getValue(b,"second")
return Add(a,b)

Python script does not restart after it crashes

I have a python script that is doing some stuff called "python1.py". Sometimes because connection issue, it crashes. I have another script called "loop.py" that is supposed to monitor the first one when it crashes and restart it. So far, it fails to restart. Meaning, when an exception is risen ( IOError or WatsonException ( I am using a Watson API ) ) the script stops
python1.py is something like this :
def mainfunction ():
a = randrange(0, 1)
Print (' my routine is doing something')
if a = 1 :
Print ('a = 1 ')
else :
Print (' a is not equals to 1')
mainfunction ()
The other script that is supposed to restart the first one is something like this :
def loopApp():
while True :
try:
python1.mainfunction ()
except IOError :
print (' IOError y')
except WatsonException :
print (' Exception from watson API')
loopApp ()
python1.py should restart when every time the exceptions happens, but it is not.
I found the way using python subprocess. It works fine and I could get expections working.
def loopApp():
loop = 1
while loop == 1:
print ("wa_loop is starting")
try:
process = subprocess.call(['python', 'wa_dir_watch.py'])
except 'IOError':
print ("\nretrying after IOError")
continue
except KeyboardInterrupt:
print ("\nstopped by user Ctr+C")
quit()
loopApp()

exit failed script run (python)

I have seen several questions about exiting a script after a task is successfully completed, but is there a way to do the same for a script which has failed? I am writing a testing script which just checks that a camera is functioning correctly. If the first test fails it is more than likely that the following tests will also fail; therefore, I want the first failure to invoke an exit and provide output to screen letting me know that there was an error.
I hope this is enough information; let me know if more details are required to help me.
Are you just looking for the exit() function?
import sys
if 1 < 0:
print >> sys.stderr, "Something is seriously wrong."
sys.exit(1)
The (optional) parameter of exit() is the return code the script will return to the shell. Usually values different than 0 signal an error.
You can use sys.exit() to exit. However, if any code higher up catches the SystemExit exception, it won't exit.
You can raise exceptions to identify error conditions. Your top-level code can catch those exceptions and handle them appropriately. You can use sys.exit to exit. E.g., in Python 2.x:
import sys
class CameraInitializationError(StandardError):
pass
def camera_test_1():
pass
def camera_test_2():
raise CameraInitializationError('Failed to initialize camera')
if __name__ == '__main__':
try:
camera_test_1()
camera_test_2()
print 'Camera successfully initialized'
except CameraInitializationError, e:
print >>sys.stderr, 'ERROR: %s' % e
sys.exit(1)
You want to check the return code from the c++ program you are running, and exit if it indicates failure. In the code below, /bin/false and /bin/true are programs that exit with error and success codes, respectively. Replace them with your own program.
import os
import sys
status = os.system('/bin/true')
if status != 0:
# Failure occurred, exit.
print 'true returned error'
sys.exit(1)
status = os.system('/bin/false')
if status != 0:
# Failure occurred, exit.
print 'false returned error'
sys.exit(1)
This assumes that the program you're running exits with zero on success, nonzero on failure.

Categories

Resources