I am downloading a file from the net, and it fails even though I am doing:
for p in query:
try: except IOError as e: print e;
If there is an error, I want to log it, and then continue on with the next file.
In this loop, I am trying to download an image, if for some reason the filename was bad, or the website was down, etc., I want to continue with the next item in the for loop.
Is there a more generic error that won't fail and continue processing?
Also, how can I log errors to a file?
It depends on the situation, but logging and then raising an exception is generally considered an antipattern. It's redundant and clutters logs. Unless you're expecting something to catch that exception and suppress the message, don't log. Pythonic is not really a look as it is the formatting of code.
To log a handled exceptionCreate the method that will generate the exception information. Use a Try...Catch block to catch the exception. Put the code that could generate an exception in the Try block. Uncomment the Dim and MsgBox lines to cause a NullReferenceException exception.
Logging an exception in python with an error can be done in the logging. exception() method. This function logs a message with level ERROR on this logger. The arguments are interpreted as for debug().
We can display the Java error messages using the logger. error("Error Message") method.
You could use the logging module:
import logging logging.basicConfig(filename='/tmp/myapp.log', level=logging.DEBUG, format='%(asctime)s %(levelname)s %(name)s %(message)s') logger=logging.getLogger(__name__) try: 1/0 except ZeroDivisionError as err: logger.error(err)
Running the script writes in /tmp/myapp.log:
% cat /tmp/myapp.log 2010-08-01 17:50:45,960 ERROR __main__ integer division or modulo by zero
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With