2009-11-02 72 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()が引数の1つを見つけられない場合、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

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

fantastic。ありがとう、これは本当に便利です。 – BeeBand

関連する問題