python 只处理 OSError Errno 13(权限被拒绝)
python Only handle OSError Errno 13 (permission denied)
我正在将一个应用程序迁移到 python3,但是有些遗留系统无法使用 python2 升级。
我有需要更新缓存文件的应用程序,但如果出于某种原因启动应用程序的用户无法 read/update 缓存。这没什么大不了的,他可以再次查询数据库而不是使用缓存。
因此,我想在 python2 上传递权限被拒绝的异常,这是一个 OSError [Errno 13]。
在 python3 上我使用 PermissionError 所以没关系。我假设这个异常只会捕获 errno 13.
这是我在 python3
上看到的
for filename in os.listdir(cache_dir):
try:
if filename.endswith('.cache'):
os.remove(os.path.join(cache_dir, filename))
Except PermissionError:
pass
Except OSError:
#handle all other errors
我如何在 python2 上模仿相同的内容,以便只有 Errno 13 是 passed
而不是其他任何东西?例如,如果它的权限被拒绝,我可以通过,但如果文件系统是只读的或磁盘已满,我就不能通过。
只有OSError
可以捕获,但是可以查看异常中包含的错误号
import errno
for filename in os.listdir(cache_dir):
# Keep the try block as focused as possible.
if not filename.endswith('.cache'):
continue
fname = os.path.join(cache_dir, filename)
try:
os.remove(fname)
except OSError as e:
if e.errno != errno.EACCES:
# handle other errors
使用 errno
模块,因为错误编号因操作系统而异。
我正在将一个应用程序迁移到 python3,但是有些遗留系统无法使用 python2 升级。
我有需要更新缓存文件的应用程序,但如果出于某种原因启动应用程序的用户无法 read/update 缓存。这没什么大不了的,他可以再次查询数据库而不是使用缓存。
因此,我想在 python2 上传递权限被拒绝的异常,这是一个 OSError [Errno 13]。 在 python3 上我使用 PermissionError 所以没关系。我假设这个异常只会捕获 errno 13.
这是我在 python3
上看到的for filename in os.listdir(cache_dir):
try:
if filename.endswith('.cache'):
os.remove(os.path.join(cache_dir, filename))
Except PermissionError:
pass
Except OSError:
#handle all other errors
我如何在 python2 上模仿相同的内容,以便只有 Errno 13 是 passed
而不是其他任何东西?例如,如果它的权限被拒绝,我可以通过,但如果文件系统是只读的或磁盘已满,我就不能通过。
只有OSError
可以捕获,但是可以查看异常中包含的错误号
import errno
for filename in os.listdir(cache_dir):
# Keep the try block as focused as possible.
if not filename.endswith('.cache'):
continue
fname = os.path.join(cache_dir, filename)
try:
os.remove(fname)
except OSError as e:
if e.errno != errno.EACCES:
# handle other errors
使用 errno
模块,因为错误编号因操作系统而异。