如何在Python(DOS上)捕获shutil.copy()的返回值?
我正在尝试记录一些复制命令的成功或失败情况,并把这些信息写入一个日志文件。我使用的是 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\i doubt this is is there.bmp'
这很好,但我能否捕捉到 "Errno 2 没有这样的文件或目录"
并把它写入日志文件呢?shutil.copy()
会返回一个整数值吗?我在Python文档中没有看到相关描述。
我想我还希望能够捕捉到返回值,这样在复制失败时脚本不会崩溃——我想让它无论出错与否都能继续运行。
谢谢。
3 个回答
2
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()
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言进行解释。
4
在Python中,你很少会看到像C语言那样的返回码来表示错误,而是通过异常来表示错误。
记录结果的正确方法是:
try:
shutil.copy(src, dest)
except EnvironmentError:
print "Error happened"
else:
print "OK"