Alichino
Alichino

Reputation: 1736

Python: catching error + printing to file

I wonder if there is a way to capture any (and all) type of error that crashes the script, but potentially without using try to catch a specific exception.

I have a webdriver script that does a lot of stuff, like clicks on links, sends keys and so on, but I cannot predict where it will crash. I want to run a series of tests in sequence and print results into a file - including any errors/crashes: Eg.

Test01 - Success!   
Test02 - NameError: name 'driver' is not defined !ERROR!
Test03 - Success!

and so on.

So that at the end I can just open the text file and check which tests need to be fixed and re-run.

Now I've been using try/exception with smaller blocks of code, but it seems to me that I would have to somehow include the whole script within try/catch/exception to get what I want.

Is there a better way to catch any type of error that is displayed after a script crashes, like on the image below:

enter image description here

Upvotes: 1

Views: 2598

Answers (2)

Hani
Hani

Reputation: 1424

It seems the trick you are looking for is redirecting the stderr to a file or stdout.

Python when having the exception will write the exception to stderr . simply you need to redirect stderr to the same output file you have when running the python program

like this

python file.py &> outputfile

Upvotes: 0

John Gordon
John Gordon

Reputation: 33275

You can use a plain except to catch any and all exceptions, like so:

try:
    some code here
except:
    print 'whoops, something went wrong'

However this doesn't give you any information about the exception, so you probably don't want to do that.

You can also catch the very broad Exception, like so:

try:
    some code here
except Exception as ex:
    print 'oops, caught this error: %s' % ex

This is a better method as it tells you what exactly went wrong.

Upvotes: 3

Related Questions