如何在Python(在DOS上)中捕获shutil.copy()的返回值?

如何在Python(在DOS上)中捕获shutil.copy()的返回值?,python,exception,logging,Python,Exception,Logging,我试图将一些复制命令的成功或失败记录到日志文件中。我正在使用shutil.copy()-例如 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) 我强制脚本中的一个复制命令失败,它生成了错误: [Err

我试图将一些复制命令的成功或失败记录到日志文件中。我正在使用
shutil.copy()
-例如

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)
我强制脚本中的一个复制命令失败,它生成了错误:

[Errno 2]没有这样的文件或目录:'X:\PJ_public\PJ_Services\BSkyB PlayJam\Content\p_NewPortal2009\1.0.0\pframes\n我怀疑这是否存在。bmp'

这很好,但是我可以捕获
“Errno 2没有这样的文件或目录”
并将其写入日志文件吗?
shutil.copy()是否返回整数值?-我没有看到Python文档中描述过这一点

我想我也希望能够捕获返回值,这样脚本就不会在复制失败时崩溃——我正试图让它继续运行,而不管出现什么错误


谢谢。

在Python中很少看到类似C的返回代码,错误由异常发出信号

测井结果的正确方法是:

try:
    shutil.copy(src, dest)
except EnvironmentError:
    print "Error happened"
else:
    print "OK"

你会想看看的。如果shutil.copy()未找到其中一个参数,将引发IOError异常。您可以从异常实例获取消息

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

非常感谢,Alex和Jamessan-我刚刚尝试了例外情况,这非常有效。太棒了。谢谢,这真的很有用。
e
的作用是什么?我认为
e
的意思是
IOError as e
,其中
as
取代了
try:
    shutil.copy(archivo, dirs)
except EnvironmentError:
    print "Error en el copiado"
    escritura = "no se pudo copiar %s a %s \n" % (archivo, dirs)
else:
    print "Copiado con exito"
    escritura = "%s --> %s \n" % (archivo, dirs)
finally:
    log = open("/tmp/errorcreararboldats.log", "a")
    log.write(escritura)
    log.close()