Python相当于Perl文件测试可读(-r),可写(-w)和可执行(-x)运算符

daw*_*awg 11 python perl operators

我一直在谷歌搜索尝试在Python中找到一些Perl的文件测试操作符.

大多数文件测试操作符只是底层操作系统stat调用的直接Python化.例如,os.stat('file').st_ctime只需将inode更改时间读取为*nix stat实用程序或ls -l将执行.

一些Perl文件测试操作符我在Python中找不到等价物.例如,我有一个由各种应用程序创建的85,000个图像文件的数据树.某些文件具有有效的UID设置,其方式很麻烦,并且修改因权限问题而失败.所以对于那些我需要运行的文件:

$ find . -type f -print0 | perl -0 -lnE 'say unless -w' | change euid...
Run Code Online (Sandbox Code Playgroud)

由于我没有在Python中找到等价物,因此我必须向Perl发现这些文件.我发现这张表显示没有直接的等价物.真正?

Wod*_*din 10

查看输出strace,perl进行stat()调用,然后getgroups()获取perl进程的补充组ID.所以它似乎只是stat()根据EUID,EGID和补充组ID 检查呼叫的结果.

Python有一个getgroups()函数os,所以我相信你也可以这样做.

编辑:如果没有人提出更好的答案,你可以尝试这样的事情.(经过严格测试):

def effectively_readable(path):
    import os, stat

    uid = os.getuid()
    euid = os.geteuid()
    gid = os.getgid()
    egid = os.getegid()

    # This is probably true most of the time, so just let os.access()
    # handle it.  Avoids potential bugs in the rest of this function.
    if uid == euid and gid == egid:
        return os.access(path, os.R_OK)

    st = os.stat(path)

    # This may be wrong depending on the semantics of your OS.
    # i.e. if the file is -------r--, does the owner have access or not?
    if st.st_uid == euid:
        return st.st_mode & stat.S_IRUSR != 0

    # See comment for UID check above.
    groups = os.getgroups()
    if st.st_gid == egid or st.st_gid in groups:
        return st.st_mode & stat.S_IRGRP != 0

    return st.st_mode & stat.S_IROTH != 0
Run Code Online (Sandbox Code Playgroud)

显然-w一个几乎相同,但有W_OK,S_IWUSR等.


Seb*_*tos 5

从Python 3.3开始,您可以执行以下操作os.access:

版本3.3中已更改:添加了dir_fd,effective_ids和follow_symlinks参数.

如果effective_ids为True,则access()将使用有效的uid/gid而不是real uid/gid执行其访问检查.您的平台可能不支持effective_ids; 您可以使用os.supports_effective_ids检查它是否可用.如果它不可用,则使用它将引发NotImplementedError.