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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1662261/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 22:49:22  来源:igfitidea点击:

How can I capture the return value of shutil.copy() in Python ( on DOS )?

pythonexceptionlogging

提问by BeeBand

I am trying to record the success or failure of a number of copy commands, into a log file. I'm using shutil.copy()- e.g.

我试图将许多复制命令的成功或失败记录到日志文件中。我正在使用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)

I forced one of the copy commands in my script to fail, and it generated the error:

我强制脚本中的其中一个复制命令失败,并产生了错误:

[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: 'X:\PJ_public\PJ_Services\BSkyB-PlayJam\Content\P_NewPortal2009\1.0.0\pframes\i doubt this is is there.bmp'

This is great, but can I capture "Errno 2 No such file or directory"and write it to a log file? Does shutil.copy()return an integer value? - I don't see this described in the Python docs.

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

I guess also I want to be able to capture the return value, so that the script doesn't bomb out on a copy failure - I'm trying to make it continue regardless of errors.

我想我也希望能够捕获返回值,这样脚本就不会在复制失败时爆炸——我试图让它继续而不考虑错误。

Thanks.

谢谢。

回答by jamessan

You'll want to look at the exceptions sectionof the Python tutorial. In the case of shutil.copy() not finding one of the arguments, an IOError exception will be raised. You can get the message from the exception instance.

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

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

回答by Alexander Lebedev

You will rarely see C-like return codes in Python, errors are signalled by exceptions instead.

你很少会在 Python 中看到类似 C 的返回码,错误由异常发出。

The correct way of logging result is:

记录结果的正确方法是:

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

回答by Pjl

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()