2009-11-02 133 views
11

我试图将一些复制命令的成功或失败记录到日志文件中。我正在使用shutil.copy() - 例如如何在Python中(在DOS上)捕获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] 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'

这是伟大的,但我可以捕捉"Errno 2 No such file or directory"并将其写入日志文件? shutil.copy()是否返回整数值? - 我没有在Python文档中看到这一点。

我想我也想能够捕获返回值,以便脚本不会在复制失败时弹出 - 我试图让它继续而不管错误。

谢谢。

回答

16

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

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

您很少会在Python中看到类似C的返回代码,而是通过异常来指示错误。

记录结果的正确的方法是:

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

非常感谢,亚历克斯和Jamessan - 我刚才想出来的例外,这工作的享受。 – BeeBand 2009-11-02 16:36:29

1
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() 
+0

太棒了。谢谢这真的很有用。 – BeeBand 2011-01-04 11:07:15