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.
shutil. copy() method is used to copy specified source (without the metadata) to the destination file or directory and it will return the path to the newly created file. The src can either be a path-like object or a string.
The shutil.copy2() method is identical to shutil.copy() except that copy2() attempts to preserve file metadata as well.
copyfile() method in Python is used to copy the content of the source file to the destination file. The metadata of the file is not copied. Source and destination must represent a file and destination must be writable.
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
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 happened"
else:
print "OK"
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