I have a custom module with a function, and I am importing it to my main file. When there is an exception raised in the module, I want to catch it in the main file.
Is this possible? I'm having a hard time finding any examples of this online or in the exception documentation.
Example:
exceptionStuff.py
class My_Error(Exception):
pass
def Fail_Func():
raise Exception
main.py
from myModules.exceptionStuff import My_Error
try:
My_Error()
except:
print('caught')
The exception doesn't get caught here.
If you reorganize exceptionStuff.py like this
class My_Error(Exception):
pass
def Fail_Func():
raise My_Error
And your main file like this
from exceptionStuff import My_Error, Fail_Func
try:
Fail_Func()
except My_Error as e:
print(e.__class__.__name__)
print('caught')
You will successfully catch an exception of type My_Error.
Output:
My_Error
caught
I want to call a function inside of an other module but i i always get the same error statement "module 'mat_import' has no attribute 'matread'".
After getting the "filename" and "button_pressed" value from the GUI I want to call matread inside of mat_import. The result should be that I have filename1 and button_pressed accessable inside of the main.py.
The main.py:
EDIT:To get "filename1" and "button_pressed" the function gui inside of GUI.py is called. This works and returns the filename to the main.py. After that i want to call matread inside of mat_import. The function matread should get the filename from the main.py and read the file. The outputs are the two variables "signals" and "signaldata".
import mat_import as mi
import GUI
filename1, button_pressed = GUI.gui()
if (button_pressed ==1):
signals, signaldata = mi.matread
The mat_import.py:
import h5py
import numpy as np
import csv
import os
import main
filename1 = ""
global matread
def matread():
#get signals and signaldata
return signals, signaldata
As mentioned in my comment, my best guess from your description of the problem and the indentation in your question is that matread() is defined within another function in the mat_import.py file. In order to make matread callable from main.py, you need to 1. define it as global and 2. execute the function that it is defined in. Alternatively, you can define matread() outside any other function, as I did with matread2 below. You can read more about variable scope here: https://matthew-brett.github.io/teaching/global_scope.html
mat_import.py:
def matread2():
return "b"
def outer_func():
global matread
def matread(): return "a"
main.py:
import mat_import as mi
try:
mi.matread()
except AttributeError as e:
print(e)
mi.outer_func()
print mi.matread()
print mi.matread2()
I'm debugging Python with Visual Studio 2015 (Python Tools extension).
I'm very new to Python and strangely when i debug the bellow code, it runs to line 18, then line 19, then line 18 again where it exits unceremoniously. Doesn't hit my catch block, doesn't hit line 20 or 21. No error message. Anyone know what might be causing this?
The unit test is testing a common google api functionality found on Git Hub here.
My Code:
import unittest
import sys
import os
import exceptions
from _multiprocessing import flags
sys.path.insert(0, "C:\Users\Jamie.Marshall\Documents\Visual Studio 2015\Projects\GetDCMPlalyStationData\DCMPSDataQuery")
try:
from dfareporting_utils import get_arguments
except ImportError:
print(ImportError.message)
print('No Import')
try:
#Line18
class Test_dfareporting_utility_test(unittest.TestCase):
#Line19
def test_A(self):
flags = get_arguments(sys.argv, __doc__, parents=[argparser])
self.assertEqual(flags[0], "")
except Exception as ex:
print(ex.message)
print(ex.source)
if __name__ == '__main__':
unittest.main()
When a class is initialized, only the signature lines of the class, the code at the top level of the class and signature lines the methods inside are executed. The code in the methods is executed only when the methods are called. An example:
E class MyClass:
|
E my_class_attribute = 1
|
E def my_method(self, a):
N b = a + 1
N return b
E = excuted; N = not executed
Your try around the class will have no effect unless an error is raised on the class or the def line.
At the result your try around the class will have no effect unless an error is raised in one of that lines.
To catch an exception in a test put the try / except inside the method. But you should actually have a defined state in your test and the error should be expected or not present, so it might be the best to expect an error and test for it with with self.assertRaises(YourErrorType):
I have a GetVars() function (not supposed to be changed), it throws sys.exit(1) in some cases.
I want to do some cleanup for this case:
try:
common_func.GetVars()
except SystemExit:
cmdline = "-user user1"
sys.argv = ['config.py', cmdline]
import config
config.py should take some args, but it contains the only print statement for now. But it is not executed - is there any way to do it? Just trying to understand what happens, I know the code looks odd :)
UPD:
now I'm trying to run
cur_dir = os.path.dirname(os.path.realpath(__file__))
gcti_cfgDir = os.path.join(cur_dir, "..", "cfg-scripts")
sys.path.append(gcti_cfgDir)
import config
try:
sys.exit(1)
except SystemExit:
try:
import config
except:
print "errr"
I tried it with this mymodule.py file:
$ cat mymodule.py
import sys
try:
sys.exit(1)
except SystemExit:
cmdline = "-user user1"
sys.argv = ['config.py', cmdline]
import config
and with this config.py file:
$ cat config.py
print "Everything is ok for now"
The result is the expected one:
$ python mymodule.py
Everything is ok for now
I am mostly sure the problem is not in the import per se, neither in the SystemExit capturing... Probably your config.py file is broken.
UPDATE: Ah, I believe I got it!
According to your new code, you are importing the config module before the sys.exit(1) and importing it in the except block, too:
import config # <-- here...
try:
sys.exit(1)
except SystemExit:
try:
import config # <-- and here
except:
print "errr"
However, the code of the module is executed just at the first import. The following ones either put the module in the namespace or, if it is already in the namespace, do nothing.
The best solution, as I see it, is to define a function inside your module. If this is the content of your module:
print "Everything is ok for now"
just replace it by
def run():
print "Everything is ok for now"
And instead of importing the module where you want it to be executed, import it only once and call the function:
import config # This line just imports, does not print nothing
config.run() # OTOH, this one prints the line...
try:
sys.exit(1)
except SystemExit:
try:
config.run() # This one prints the line too
except:
print "errr"
Actually, this is surely the best way of dealing with code in Python: put code into functions, put functions into modules, call the functions. It is not generally a good practice to put your executable code directly inside the module, as you were trying to do.
2nd UPDATE: If you cannot change the code of the config.py module, you can still call it using subprocess.call to call the Python interpreter. You can even pass the parameters you were trying to add to sys.argv:
import subprocess
# ...
subprocess.call(['python', 'config.py'])
try:
sys.exit(1)
except SystemExit:
try:
subprocess.call(['python', 'config.py', "-user", "user1"]) # Extra args
except:
print "errr"
Use the atexit module to register cleanup handlers or if you're sure that GetVars is calling sys.exit, monkey patch the latter to throw a custom exception instead of really running so that you can catch it and manually handle it.
How can I log my Python exceptions?
try:
do_something()
except:
# How can I log my exception here, complete with its traceback?
Use logging.exception from within the except: handler/block to log the current exception along with the trace information, prepended with a message.
import logging
LOG_FILENAME = '/tmp/logging_example.out'
logging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG)
logging.debug('This message should go to the log file')
try:
run_my_stuff()
except:
logging.exception('Got exception on main handler')
raise
Now looking at the log file, /tmp/logging_example.out:
DEBUG:root:This message should go to the log file
ERROR:root:Got exception on main handler
Traceback (most recent call last):
File "/tmp/teste.py", line 9, in <module>
run_my_stuff()
NameError: name 'run_my_stuff' is not defined
Use exc_info options may be better, remains warning or error title:
try:
# coode in here
except Exception as e:
logging.error(e, exc_info=True)
My job recently tasked me with logging all the tracebacks/exceptions from our application. I tried numerous techniques that others had posted online such as the one above but settled on a different approach. Overriding traceback.print_exception.
I have a write up at http://www.bbarrows.com/ That would be much easier to read but Ill paste it in here as well.
When tasked with logging all the exceptions that our software might encounter in the wild I tried a number of different techniques to log our python exception tracebacks. At first I thought that the python system exception hook, sys.excepthook would be the perfect place to insert the logging code. I was trying something similar to:
import traceback
import StringIO
import logging
import os, sys
def my_excepthook(excType, excValue, traceback, logger=logger):
logger.error("Logging an uncaught exception",
exc_info=(excType, excValue, traceback))
sys.excepthook = my_excepthook
This worked for the main thread but I soon found that the my sys.excepthook would not exist across any new threads my process started. This is a huge issue because most everything happens in threads in this project.
After googling and reading plenty of documentation the most helpful information I found was from the Python Issue tracker.
The first post on the thread shows a working example of the sys.excepthook NOT persisting across threads (as shown below). Apparently this is expected behavior.
import sys, threading
def log_exception(*args):
print 'got exception %s' % (args,)
sys.excepthook = log_exception
def foo():
a = 1 / 0
threading.Thread(target=foo).start()
The messages on this Python Issue thread really result in 2 suggested hacks. Either subclass Thread and wrap the run method in our own try except block in order to catch and log exceptions or monkey patch threading.Thread.run to run in your own try except block and log the exceptions.
The first method of subclassing Thread seems to me to be less elegant in your code as you would have to import and use your custom Thread class EVERYWHERE you wanted to have a logging thread. This ended up being a hassle because I had to search our entire code base and replace all normal Threads with this custom Thread. However, it was clear as to what this Thread was doing and would be easier for someone to diagnose and debug if something went wrong with the custom logging code. A custome logging thread might look like this:
class TracebackLoggingThread(threading.Thread):
def run(self):
try:
super(TracebackLoggingThread, self).run()
except (KeyboardInterrupt, SystemExit):
raise
except Exception, e:
logger = logging.getLogger('')
logger.exception("Logging an uncaught exception")
The second method of monkey patching threading.Thread.run is nice because I could just run it once right after __main__ and instrument my logging code in all exceptions. Monkey patching can be annoying to debug though as it changes the expected functionality of something. The suggested patch from the Python Issue tracker was:
def installThreadExcepthook():
"""
Workaround for sys.excepthook thread bug
From
http://spyced.blogspot.com/2007/06/workaround-for-sysexcepthook-bug.html
(https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1230540&group_id=5470).
Call once from __main__ before creating any threads.
If using psyco, call psyco.cannotcompile(threading.Thread.run)
since this replaces a new-style class method.
"""
init_old = threading.Thread.__init__
def init(self, *args, **kwargs):
init_old(self, *args, **kwargs)
run_old = self.run
def run_with_except_hook(*args, **kw):
try:
run_old(*args, **kw)
except (KeyboardInterrupt, SystemExit):
raise
except:
sys.excepthook(*sys.exc_info())
self.run = run_with_except_hook
threading.Thread.__init__ = init
It was not until I started testing my exception logging I realized that I was going about it all wrong.
To test I had placed a
raise Exception("Test")
somewhere in my code. However, wrapping a a method that called this method was a try except block that printed out the traceback and swallowed the exception. This was very frustrating because I saw the traceback bring printed to STDOUT but not being logged. It was I then decided that a much easier method of logging the tracebacks was just to monkey patch the method that all python code uses to print the tracebacks themselves, traceback.print_exception.
I ended up with something similar to the following:
def add_custom_print_exception():
old_print_exception = traceback.print_exception
def custom_print_exception(etype, value, tb, limit=None, file=None):
tb_output = StringIO.StringIO()
traceback.print_tb(tb, limit, tb_output)
logger = logging.getLogger('customLogger')
logger.error(tb_output.getvalue())
tb_output.close()
old_print_exception(etype, value, tb, limit=None, file=None)
traceback.print_exception = custom_print_exception
This code writes the traceback to a String Buffer and logs it to logging ERROR. I have a custom logging handler set up the 'customLogger' logger which takes the ERROR level logs and send them home for analysis.
You can log all uncaught exceptions on the main thread by assigning a handler to sys.excepthook, perhaps using the exc_info parameter of Python's logging functions:
import sys
import logging
logging.basicConfig(filename='/tmp/foobar.log')
def exception_hook(exc_type, exc_value, exc_traceback):
logging.error(
"Uncaught exception",
exc_info=(exc_type, exc_value, exc_traceback)
)
sys.excepthook = exception_hook
raise Exception('Boom')
If your program uses threads, however, then note that threads created using threading.Thread will not trigger sys.excepthook when an uncaught exception occurs inside them, as noted in Issue 1230540 on Python's issue tracker. Some hacks have been suggested there to work around this limitation, like monkey-patching Thread.__init__ to overwrite self.run with an alternative run method that wraps the original in a try block and calls sys.excepthook from inside the except block. Alternatively, you could just manually wrap the entry point for each of your threads in try/except yourself.
You can get the traceback using a logger, at any level (DEBUG, INFO, ...). Note that using logging.exception, the level is ERROR.
# test_app.py
import sys
import logging
logging.basicConfig(level="DEBUG")
def do_something():
raise ValueError(":(")
try:
do_something()
except Exception:
logging.debug("Something went wrong", exc_info=sys.exc_info())
DEBUG:root:Something went wrong
Traceback (most recent call last):
File "test_app.py", line 10, in <module>
do_something()
File "test_app.py", line 7, in do_something
raise ValueError(":(")
ValueError: :(
EDIT:
This works too (using python 3.6)
logging.debug("Something went wrong", exc_info=True)
What I was looking for:
import sys
import traceback
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback_in_var = traceback.format_tb(exc_traceback)
See:
https://docs.python.org/3/library/traceback.html
Uncaught exception messages go to STDERR, so instead of implementing your logging in Python itself you could send STDERR to a file using whatever shell you're using to run your Python script. In a Bash script, you can do this with output redirection, as described in the BASH guide.
Examples
Append errors to file, other output to the terminal:
./test.py 2>> mylog.log
Overwrite file with interleaved STDOUT and STDERR output:
./test.py &> mylog.log
Here is a version that uses sys.excepthook
import traceback
import sys
logger = logging.getLogger()
def handle_excepthook(type, message, stack):
logger.error(f'An unhandled exception occured: {message}. Traceback: {traceback.format_tb(stack)}')
sys.excepthook = handle_excepthook
This is how I do it.
try:
do_something()
except:
# How can I log my exception here, complete with its traceback?
import traceback
traceback.format_exc() # this will print a complete trace to stout.
maybe not as stylish, but easier:
#!/bin/bash
log="/var/log/yourlog"
/path/to/your/script.py 2>&1 | (while read; do echo "$REPLY" >> $log; done)
To key off of others that may be getting lost in here, the way that works best with capturing it in logs is to use the traceback.format_exc() call and then split this string for each line in order to capture in the generated log file:
import logging
import sys
import traceback
try:
...
except Exception as ex:
# could be done differently, just showing you can split it apart to capture everything individually
ex_t = type(ex).__name__
err = str(ex)
err_msg = f'[{ex_t}] - {err}'
logging.error(err_msg)
# go through the trackback lines and individually add those to the log as an error
for l in traceback.format_exc().splitlines():
logging.error(l)
Heres a simple example taken from the python 2.6 documentation:
import logging
LOG_FILENAME = '/tmp/logging_example.out'
logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG,)
logging.debug('This message should go to the log file')