如何在 python 中捕获异常中的异常?
考虑以下情况
bak_filename = filename + ".bak"
#This try is needed because if bak_filename existed, rename will fail
try:
os.rename(filename, bak_filename)
except WindowsError:
#However, os.remove may still fail e.g. file in use. How would you handle this exception within except clause ?
#try and except around this os.remove?
os.remove(bak_filename)
os.rename(filename, bak_filename)
任何想法:
重写以避免重复尝试?
不一定是这个例子,但在某些情况下我们无法重写,你会如何处理双try?
最佳答案
避免所有这些异常包装的解决方案是使用 shutil.move
shutil.move(filename, bak_filename)
If the destination already exists but is not a directory, it may be overwritten depending on os.rename() semantics.
If the destination is on the current filesystem, then os.rename() is used. Otherwise, src is copied to dst using copy_function and then removed. In case of symlinks, a new symlink pointing to the target of src will be created in or as dst and src will be removed.
所以它基本上完成了您想要做的事情,但是在所有 python 发行版上都可用的库中。
请注意,如果文件很大并且目标文件存在并且os.rename
拒绝覆盖它,性能可能会很差(完全取决于操作系统,但例如,Windows 将拒绝对现有文件进行重命名),因为当 os.rename 抛出 OSError 时,后备措施是复制源,然后删除。该实现不会尝试删除文件然后再次重命名,因为如果重命名
失败,Python会假设我们正在尝试跨文件系统重命名,并且复制+删除在这种情况下是正确的(这正是 Unix mv
的工作原理)。
try:
os.rename(src, real_dst)
except OSError:
if os.path.islink(src):
...
else:
copy_function(src, real_dst)
os.unlink(src)
要解决可能存在的文件问题,可以先将 os.remove
调用包装在 try/except OSError
语句中。
try:
os.remove(bak_filename)
except OSError:
pass
shutil.move(filename, bak_filename) # or os.rename(filename, bak_filename)
当然,如果bak_filename
被锁定/不可删除,shutil.mode
仍然可以引发异常。另请注意,如果我们尝试删除目标文件,os.rename
将与 shutil.move
一样好。如果目标文件无法删除,则操作无论如何也无法成功。
关于python - 如何在 except 子句中捕获 python 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58492795/