我正在学习python 3并尝试编写一个脚本来复制一个目录。我用的是shutil.copytree。从python文档中可以看出:
If exception(s) occur, an Error is raised with a list of reasons.
This exception collects exceptions that are raised during a multi-file
operation. For copytree(), the exception argument is a list of
3-tuples (srcname, dstname, exception).
在示例中,他们这样做:
except Error as err:
errors.extend(err.args[0])
这是我的剧本:
def copyDirectory(src, dest):
errors = []
try:
shutil.copytree(src, dest)
except Error as err:
errors.extend(err.args[0])
source="C:/Users/MrRobot/Desktop/Copy"
destination="C:/Users/MrRobot/Desktop/Destination"
copyDirectory(source, destination)
moveDirectory(destination,"I:/")
问题:
在使用shutil.copytree时,如何正确捕获可能发生的异常(假设我的上述脚本不正确)?
那么,您将如何查看发生的错误,我将循环遍历errors数组?
捕获异常时,需要包含模块名:
except shutil.Error as err:
或者直接导入:
from shutil import copytree, Error
# the rest of your code...
try:
copytree(src, dest)
except Error as err:
errors.extend(err.args[0])
要查看回溯和异常信息,您有几个选项:
不要抓住例外。您的脚本将停止,所有错误信息将被打印出来。
如果您希望脚本继续,那么您实际上是在问这个so问题的副本。我会提到那个问题;被接受的答案写得很好。
顺便说一下,您应该避免将其称为数组。这个特殊的异常对象有一个元组列表,数组是一个完全不同的数据结构。
快速问题,那么我该如何查看错误,只需遍历错误数组?
@mrrobot请参见编辑。
你能告诉我,为了我自己的理解,如何实现回溯特性吗?
@mrrobot python是开源的。什么阻止了您查看它们的实现?
您可以使用oserror来处理它:
import shutil
def removeDirectory(directory):
try:
shutil.rmtree(directory)
except OSError as err:
print(err)
removeDirectory('PathOfDirectoryThatDoesntExist')
输出:
[Errno 2] No such file or directory:
'./PathOfDirectoryThatDoesntExist'