python - 在python中检查文件的权限

标签 python python-2.7 error-handling file-permissions

我正在尝试检查给定指定路径的文件的可读性。这是我拥有的:

def read_permissions(filepath):
    '''Checks the read permissions of the specified file'''
    try:
        os.access(filepath, os.R_OK) # Find the permissions using os.access
    except IOError:
        return False

    return True

这有效并在运行时返回 True 或 False 作为输出。但是,我希望 errno 的错误消息伴随它。这是我认为我必须做的(但我知道有问题):

def read_permissions(filepath):
    '''Checks the read permissions of the specified file'''
    try:
        os.access(filepath, os.R_OK) # Find the permissions using os.access
    except IOError as e:
        print(os.strerror(e)) # Print the error message from errno as a string

    print("File exists.")

但是,如果我输入一个不存在的文件,它会告诉我该文件存在。有人可以帮助我了解我做错了什么(以及我将来可以做些什么来避免这个问题)?我还没有看到有人尝试使用 os.access。我也愿意接受其他选项来测试文件的权限。有人可以帮助我在出现问题时如何提出适当的错误消息吗?

此外,这可能适用于我的其他功能(他们在检查其他内容时仍然使用 os.access,例如使用 os.F_OK 的文件是否存在以及使用 os.W_OK 的文件的写入权限)。这是我试图模拟的事物的示例:

>>> read_permissions("located-in-restricted-directory.txt") # Because of a permission error (perhaps due to the directory)
[errno 13] Permission Denied
>>> read_permissions("does-not-exist.txt") # File does not exist
[errno 2] No such file or directory

这是我试图通过向问题返回适当的错误消息来模拟的事情。我希望这有助于避免对我的问题产生任何混淆。

我可能应该指出,虽然我已经阅读了 os.access 文档,但我并不想稍后打开该文件。我只是想创建一个模块,其中一些组件用于检查特定文件的权限。我有一个基线(我提到的第一段代码)作为我其余代码的决策者。在这里,我只是想再次编写它,但要以一种用户友好的方式(不仅仅是 TrueFalse,而是包含完整的消息)。由于 IOError 可以通过几种不同的方式出现(例如权限被拒绝或目录不存在),我试图让我的模块识别并发布问题。我希望这可以帮助您帮助我确定任何可能的解决方案。

最佳答案

os.access 在文件不存在时返回 False,无论传递的模式参数如何。

这在 the documentation for os.access 中没有明确说明但这并不是非常令人震惊的行为;毕竟,如果一个文件不存在,您就不可能访问它。检查the access(2) man page正如文档所建议的那样,它提供了另一条线索,因为 access 在各种条件下都会返回 -1 。无论如何,你可以像我一样简单地在 IDLE 中检查返回值:

>>> import os
>>> os.access('does_not_exist.txt', os.R_OK)
False

在 Python 中,通常不鼓励在尝试实际做有用的事情之前四处检查类型等。这种理念通常用首字母缩写词 EAFP 来表达,它代表Easier to Ask Forgiveness than Permission。如果您再次引用文档,您会发现这在当前情况下特别相关:

Note: Using access() to check if a user is authorized to e.g. open a file before actually doing so using open() creates a security hole, because the user might exploit the short time interval between checking and opening the file to manipulate it. It’s preferable to use EAFP techniques. For example:

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()
return "some default data"

is better written as:

try:
    fp = open("myfile")
except IOError as e:
    if e.errno == errno.EACCES:
        return "some default data"
    # Not a permission error.
    raise
else:
    with fp:
        return fp.read()

如果您有其他原因检查权限而不是在调用 open() 之前猜测用户,您可以查看 How do I check whether a file exists using Python?一些建议。请记住,如果您确实需要引发异常,您始终可以自己引发;无需去野外狩猎。


Since the IOError can be brought up a couple different ways (such as permission denied, or non-existent directory), I am trying to get my module to identify and publish the issue.

这就是上面第二种方法所做的。见:

>>> try:
...     open('file_no_existy.gif')
... except IOError as e:
...     pass
...
>>> e.args
(2, 'No such file or directory')
>>> try:
...     open('unreadable.txt')
... except IOError as e:
...     pass
...
>>> e.args
(13, 'Permission denied')
>>> e.args == (e.errno, e.strerror)
True

但是您需要选择一种方法。如果您请求宽恕,请在 try-except block 中做这件事(打开文件)并适本地处理后果。如果你成功了,那么你就知道你成功了,因为没有异常(exception)。

另一方面,如果您以这种或另一种方式征求许可(又名 LBYL,三思而后行),您仍然不知道是否您可以成功打开该文件,直到您真正打开它为止。如果文件在您检查其权限后被移动怎么办?如果有一个您不想检查的问题怎么办?

如果你还想请求许可,不要使用try-except;你没有做这件事,所以你不会抛出错误。相反,使用条件语句调用 os.access 作为条件。

关于python - 在python中检查文件的权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27434643/

相关文章:

javascript - 从抓取的 Javascript 表列表创建 DataFrame

node.js - 处理 CronJob 执行函数中的错误

Jquery 错误处理选项

python - Paramiko exec_command stdout、stderr、stdin 到日志记录器

java - 用于创建工程图的库/语言

python - BFS 和 UCS 算法。我的 BFS 实现有效,但我的 UCS 无效。不知道为什么

python - 组合可能的不同数据格式列表

javascript - bluebirdjs协程错误处理(浏览器)

python - 我如何确保 Graphviz 可执行文件在我系统的路径上?

python - 触发 PySide QTabWidget 中选项卡的关闭事件