2009-11-02 132 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