Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I capture the return value of shutil.copy() in Python ( on DOS )?

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.

like image 413
BeeBand Avatar asked Nov 02 '09 16:11

BeeBand


People also ask

What is Shutil copy return?

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.

What's the difference between Shutil copy and Shutil copy?

The shutil.copy2() method is identical to shutil.copy() except that copy2() attempts to preserve file metadata as well.

How do you use the copy command in Python?

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.


2 Answers

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
like image 57
jamessan Avatar answered Oct 24 '22 20:10

jamessan


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"
like image 35
Alexander Lebedev Avatar answered Oct 24 '22 19:10

Alexander Lebedev