【问题标题】:How can I capture the return value of shutil.copy() in Python ( on DOS )?如何在 Python 中(在 DOS 上)捕获 shutil.copy() 的返回值?
【发布时间】:2010-12-12 08:18:59
【问题描述】:

我正在尝试将多个复制命令的成功或失败记录到日志文件中。我正在使用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 文档中没有看到这一点。

我想我也希望能够捕获返回值,这样脚本就不会因复制失败而崩溃——我试图让它继续运行,不管错误如何。

谢谢。

【问题讨论】:

    标签: python exception logging


    【解决方案1】:

    您需要查看Python tutorial 的exceptions section。在 shutil.copy() 找不到参数之一的情况下,将引发 IOError 异常。您可以从异常实例中获取消息。

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

    【讨论】:

    • e 是干什么用的?
    • 我认为 e 应该是 IOError as e 其中 as 替换 ,
    【解决方案2】:

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

    记录结果的正确方式是:

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

    【讨论】:

    • 非常感谢,Alex 和 Jamessan - 我刚刚尝试了例外情况,这是一种享受。
    【解决方案3】:
    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()
    

    【讨论】:

    • 太棒了。谢谢,这真的很有用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-09
    • 2010-10-03
    • 1970-01-01
    • 1970-01-01
    • 2012-11-16
    • 2014-09-08
    • 1970-01-01
    相关资源
    最近更新 更多