【问题标题】:Try statement not catching copy error python尝试语句未捕获复制错误python
【发布时间】:2012-07-04 16:56:11
【问题描述】:

我是一个初学者 python 程序员,用它来完成简单的管理任务。

我编写了一个小日志移动代码(因为我有一个系统会生成大量从服务器移动到存储的日志文件)。

我在远程路径上的文件上遇到权限错误,尝试复制时权限被拒绝,因此将其包装在 try: 语句中以尝试并绕过错误,但脚本仍在结束...第 32 行是shutil.copy2(位置,复制位置)。

基本路径是本地目录,日志目录是 UNC 路径(附加文件夹集)。文件夹在脚本前面的两个文件系统中镜像。 (所以应该一直存在)。

os.remove 周围的其他尝试都可以。

如果有人能指出我大致的方向,将不胜感激。

Traceback (most recent call last):
  File "C:\Program Files (x86)\Log Mover\log_mover.py", line 32,
  shutil.copy2 (location,copylocation)
  File "C:\Python27\lib\shutil.py", line 127, in copy2
  copyfile(src, dst)
  File "C:\Python27\lib\shutil.py", line 82, in copyfile
    with open(dst, 'wb') as fdst:
  IOError: [Errno 13] Permission denied: '\\\\XXXX\\d$\\logs\\
  logs/XXX\\XXX - 2012-07-03 21-49.XXXX'
  ☀could not delete:C:/logs/XX\XXX\XXX 2012-07-04 08-00-42.txt
  Traceback (most recent call last):


for root, dirs, files in os.walk(basepath):
   for filenames in files:
        location = os.path.join(root, filenames)
        try:
            datemod = time.strftime("%Y%m%d%H",time.localtime(os.path.getmtime(location)))
        except OSError:
            print "count not get mod time:"+location
        if datemod != currtime:
            drive,path = os.path.splitdrive(location)
            copylocation = str(logdir)+str(path)
            try:
                shutil.copy2 (location,copylocation)
            except OSError:
                print "could not copy"
            pass

            if os.path.getsize(location) == os.path.getsize(copylocation):
                try:
                    os.remove(location)
                    print "Deleted"+location
                except OSError:
                    print "could not delete:"+location
                pass
            else:
                print "sizes dont match"

谢谢

肯尼

【问题讨论】:

  • 你必须抓住IOError 而不是OSError

标签: python


【解决方案1】:

当你得到 IOError 时,你正试图捕捉 OSError。

添加这个:

except (OSError, IOError):
    #some code

【讨论】:

  • 在 Python 3.3 中,所有这些错误都将合并到 OSError 下。
【解决方案2】:

shutil.copy2 抛出 IOError,但你正在捕捉 OSErrors,因此它只是冒泡过去,未被捕获。

【讨论】:

    猜你喜欢
    • 2019-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-15
    • 1970-01-01
    • 2018-04-20
    • 1970-01-01
    相关资源
    最近更新 更多