在python中检查文件的权限 [英] Check the permissions of a file in python

查看:144
本文介绍了在python中检查文件的权限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to check the readability of a file given the specified path. Here's what I have:

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 的错误消息伴随它。这是我认为我必须做的(但我知道有问题):

This works and returns True or False as the output when run. However, I want the error messages from errno to accompany it. This is what I think I would have to do (But I know that there is something wrong):

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 尝试此操作。我也开放其他选项来测试文件的权限。有人可以在出现问题时帮助我如何发出适当的错误消息吗?

However, if I were to type in a file that does not exist, it tells me that the file exists. Can someone help me as to what I have done wrong (and what I can do to stay away from this issue in the future)? I haven't seen anyone try this using os.access. I'm also open to other options to test the permissions of a file. Can someone help me in how to raise the appropriate error message when something goes wrong?

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

Also, this would likely apply to my other functions (They still use os.access when checking other things, such as the existence of a file using os.F_OK and the write permissions of a file using os.W_OK). Here is an example of the kind of thing that I am trying to simulate:

>>> 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

这是我尝试通过向问题返回适当的错误消息来模拟的事情。我希望这将有助于避免对我的问题感到困惑。

This is the kind of thing that I am trying to simulate, by returning the appropriate error message to the issue. I hope that this will help avoid any confusion about my question.

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

I should probably point out that while I have read the os.access documentation, I am not trying to open the file later. I am simply trying to create a module in which some of the components are to check the permissions of a particular file. I have a baseline (The first piece of code that I had mentioned) which serves as a decision maker for the rest of my code. Here, I am simply trying to write it again, but in a user-friendly way (not just True or just False, but rather with complete messages). 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. I hope that this helps you to help me determine any possible solutions.

推荐答案

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

os.access returns False when the file does not exist, regardless of the mode parameter passed.

os.access ,但这并不是非常令人震惊的行为;毕竟,如果文件不存在,则可能无法访问它。根据文档建议检查 access(2)手册页提供了另一个线索,因为在各种情况下,访问返回 -1 。无论如何,您都可以像我一样简单地检查IDLE中的返回值:

This isn't stated explicitly in the documentation for os.access but it's not terribly shocking behavior; after all, if a file doesn't exist, you can't possibly access it. Checking the access(2) man page as suggested by the docs gives another clue, in that access returns -1 in a wide variety of conditions. In any case, you can simply do as I did and check the return value in IDLE:

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

在Python中通常不建议在尝试实际做有用的事情之前先检查类型等。这种哲学通常用缩写词EAFP来表达,它代表比许可更容易寻求宽恕。如果再次参考文档,您会发现这在当前情况下尤其重要:

In Python it's generally discouraged to go around checking types and such before trying to actually do useful things. This philosophy is often expressed with the initialism EAFP, which stands for Easier to Ask Forgiveness than Permission. If you refer to the docs again, you'll see this is particularly relevant in the present case:


注意:使用 access()检查用户是否被授权进行例如在使用 open()进行实际操作之前先打开文件会创建一个安全的
漏洞,因为用户可能会利用
检查和打开之间的较短时间间隔该文件进行操作。最好使用
EAFP 技术。例如:

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"

最好写成:

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()之前猜测用户之外,还有其他检查权限的原因,则可以请参阅如何使用Python检查文件是否存在?以获得一些建议。请记住,如果您确实需要引发异常,则可以随时自己引发

If you have other reasons for checking permissions than second-guessing the user before calling open(), you could look to How do I check whether a file exists using Python? for some suggestions. Remember that if you really need an exception to be raised, you can always raise it yourself; no need to go hunting for one in the wild.


因为可以带出IOError通过几种不同的方式(例如
权限被拒绝或目录不存在),我正在尝试让我的
模块来识别和发布问题。

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.

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

That's what the second approach above does. See:

>>> 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块中执行该操作(打开文件),并适当处理后果。如果您成功了,那么您就知道您成功了,因为没有例外。

But you need to pick one approach or the other. If you're asking forgiveness, do the thing (open the file) in a try-except block and deal with the consequences appropriately. If you succeed, then you know you succeeded because there's no exception.

另一方面,如果您请求许可(又名LBYL,请先了解一下),以另一种方式,您仍然在真正执行之前不知道是否可以成功打开该文件。如果在检查其权限后文件被移动,该怎么办?

On the other hand, if you ask permission (aka LBYL, Look Before You Leap) in this that and the other way, you still don't know if you can successfully open the file until you actually do it. What if the file gets moved after you check its permissions? What if there's a problem you didn't think to check for?

如果您仍然想征求许可,请不要使用try-except;否则,怎么办?您不会在做事情,因此您不会抛出错误。而是使用条件语句,并以 os.access 作为条件。

If you still want to ask permission, don't use try-except; you're not doing the thing so you're not going to throw errors. Instead, use conditional statements with calls to os.access as the condition.

这篇关于在python中检查文件的权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆