【问题标题】:Is there a way to check access with pathlib?有没有办法用 pathlib 检查访问?
【发布时间】:2020-10-24 23:08:46
【问题描述】:

我现在正在使用 pathlib,这让我做很多事情变得更容易。 但我仍然缺少 os.access 方法。有没有办法使用 pathlib?

from os import access, R_OK
from pathlib import Path



def check_access(path):
    return access(path, R_OK)

path='path'

if check_access(path):
    print("Path is available")

else:
    print("Path isn't available")

【问题讨论】:

  • 不,因为这个问题的目标是一个 pathlib 解决方案。这显示了我实际在做什么。
  • 另一个问题的目标也是一个pathlib的解决方案。这是同一个问题。抱歉,投票关闭时自动生成的评论不是很好。
  • “自动生成的评论”?您是否在您发布的链接中找到了达到目标的答案?
  • 我的第一条评论是在我投票关闭问题时自动生成的。我这样做是因为这是同一个问题。显然还没有人写出你觉得满意的答案,但这并不能改变这个问题已经存在且不应重复的事实。

标签: python python-3.x operating-system pathlib


【解决方案1】:

根据以下链接中的信息,我创建了此代码:

from pathlib import Path

def check_access(path, mode=None):
    print(oct(path.stat().st_mode))
    stat = oct(path.stat().st_mode)[2:]
    if len(stat) <= 5:
        stat = f'0{stat}'
        print(stat)
    per_user  = stat[3]
##    per_group = stat[4]
##    per_other = stat[5]


    if mode == 'F_OK':
        return path.exists()
    #is it equally to 040for dir 100 for file?
    if mode == 'R_OK':
        if per_user >='4':
            return True
    if mode == 'W_OK':
        if per_user == 2 or 6 or 7:
            return True
    if mode == 'X_OK':
        if int(stat) % 2:
            return True

path = Path('directory')

if check_access(path, 'W_OK'):
    print("Path is available")

else:
    print("Path isn't available")

也许有人知道用 pathlib 解决这个问题的更好方法,或者可以教我更好地理解 stat 方法。

http://permissions-calculator.org/

https://en.wikipedia.org/wiki/File_system_permissions

Better assertEqual() for os.stat(myfile).st_mode

How can I get the Unix permission mask from a file? https://docs.python.org/3/library/pathlib.html#pathlib.Path.stat

【讨论】:

  • 这假定文件的所有者是执行代码的 python 进程的所有者。我认为首先需要检查os.getuid() 是否与path.stat_uid() 相同以及相应的权限。如果不是,则检查 os.getuid() 是否属于 path.stat_gid() 并相应地获得组权限。如果这两个都失败,则检查其他访问权限。
  • @tachyon 您无法使用 pathlib 获取 user id,但您可以找出谁是所有者或该文件属于哪个组。与Path.owner()Path.group()。因此,对我来说,这种情况下使用 pathlib 的独家解决方案似乎是可能的。
猜你喜欢
  • 1970-01-01
  • 2011-04-20
  • 1970-01-01
  • 2010-10-27
  • 2017-04-20
  • 2018-11-08
  • 1970-01-01
  • 1970-01-01
  • 2015-08-12
相关资源
最近更新 更多