How to write an error to a file and not cause an exception error

I download a file from the network and it fails even if I do:

for p in the request:

try: except IOError as e: print e; 

If there is an error, I want to register it, and then continue from the next file.

In this loop, I am trying to load an image if for some reason the file name was bad or the website was unavailable, etc., I want to continue the next element in the for loop.

Is there a more general error that won't work and will continue processing?

Also, how can I log errors in a file?

+17
python logging exception
source share
4 answers

As pointed out by Lott, if the download fails, if the problem is not fixed upstream (or with your download address), the best thing you can do is try again. However, if the situation is that you have a list of downloads, and just want to skip failed downloads instead of exiting, then:

 logf = open("download.log", "w") for download in download_list: try: # code to process download here except Exception as e: # most generic exception you can catch logf.write("Failed to download {0}: {1}\n".format(str(download), str(e))) # optional: delete local version of failed download finally: # optional clean up code pass 

Notes:

(1) Using the " logging " module, as suggested by ~ unutbu, gives you more flexibility and power with log output, including a time stamp, while recording on different channels (e.g. stderr, file) depending on the level of errors, etc. etc.

(2) You may consider implementing the above logic using the " with " construct.

+13
source share

You can use 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 entry in /tmp/myapp.log:

 % cat /tmp/myapp.log 2010-08-01 17:50:45,960 ERROR __main__ integer division or modulo by zero 
+15
source share

It catches everything. But it is much better to catch the exact exception. python <= 2.7

 while True: try: doStuff() except Exception, e: f = open('log.txt', 'w') f.write('An exceptional thing happed - %s' % e) f.close() 
+3
source share

This will write your error to the log file and continue executing the code.

 import traceback #This line opens a log file log = open("log.txt", "w") try: # some code # Below line will print any print to log file as well. print("Creating DB Connection", file = log) except Exception: traceback.print_exc(file=log) continue 
+2
source share

All Articles