views:

287

answers:

2

Hi,

I am trying to record the success or failure of a number of copy commands, into a log file. I'm using shutil.copy() - e.g.

        `str_list.append(getbitmapsfrom) 
         game.bigbitmap = "i doubt this is there.bmp"
         str_list.append(game.bigbitmap)
         source = '\\'.join(str_list)
         shutil.copy (source, newbigbmpname)`

I forced one of the copy commands in my script to fail, and it generated the error:

[Errno 2] No such file or directory: 'X:\PJ_public\PJ_Services\BSkyB-PlayJam\Content\P_NewPortal2009\1.0.0\pframes\i doubt this is is there.bmp'

This is great, but can I capture "Errno 2 No such file or directory" and write it to a log file? Does shutil.copy() return an integer value? - I don't see this described in the Python docs.

I guess also I want to be able to capture the return value, so that the script doesn't bomb out on a copy failure - I'm trying to make it continue regardless of errors.

Thanks.

+3  A: 

You will rarely see C-like return codes in Python, errors are signalled by exceptions instead.

The correct way of logging result is:

try:
    shutil.copy(src, dest)
except EnvironmentError:
    print "Error happended"
else:
    print "OK"
Alex Lebedev
many thanks, Alex and Jamessan - I have just tried out the exceptions and this works a treat.
BeeBand
+5  A: 

You'll want to look at the exceptions section of the Python tutorial. In the case of shutil.copy() not finding one of the arguments, an IOError exception will be raised. You can get the message from the exception instance.

try:
    shutil.copy(src, dest)
except IOError, e:
    print "Unable to copy file. %s" % e
jamessan