【问题标题】:python Only handle OSError Errno 13 (permission denied)python 仅处理 OSError Errno 13 (权限被拒绝)
【发布时间】:2022-01-06 23:19:32
【问题描述】:

我正在将应用程序迁移到 python3,但有些遗留系统无法使用 python2 升级。

我的应用程序需要更新缓存文件,但如果由于某种原因启动应用程序的用户无法读取/更新缓存。没什么大不了的,他可以再次查询数据库而不是使用缓存。

因此,我想通过 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 而不是其他任何东西?例如,如果权限被拒绝,我可以通过,但如果 fs 是只读的或磁盘已满,则不能通过。

【问题讨论】:

    标签: python exception


    【解决方案1】:

    只有OSError可以catch,但是可以查看异常中包含的错误号。

    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 模块,因为错误编号因操作系统而异。

    【讨论】:

    • EPERM 表示不允许操作,而 Eaccess 表示根据virtsync.com/c-error-codes-include-errno 拒绝权限,当我测试代码时,我得到 13 作为 e.errno。所以我应该使用 EACES 对吗?
    • 可能我没仔细看:)
    • 其实好像有点暧昧。 PermissionError 记录为对应于 both 错误号。但在这种情况下,EACCES 似乎是正确的。
    猜你喜欢
    • 2014-07-15
    • 2015-09-14
    • 1970-01-01
    • 2018-02-05
    • 2017-04-20
    • 2021-05-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多