python 检查python中目录的权限

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/704945/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 20:42:07  来源:igfitidea点击:

check permissions of directories in python

pythonchmod

提问by vartec

i want a python program that given a directory, it will return all directories within that directory that have 775 (rwxrwxr-x) permissions

我想要一个给定目录的 python 程序,它将返回该目录中具有 775 ( rwxrwxr-x) 权限的所有目录

thanks!

谢谢!

回答by lt_kije

Neither answer recurses, though it's not entirely clear that that's what the OP wants. Here's a recursive approach (untested, but you get the idea):

这两个答案都不会重复,尽管并不完全清楚这就是 OP 想要的。这是一种递归方法(未经测试,但您明白了):

import os
import stat
import sys

MODE = "775"

def mode_matches(mode, file):
    """Return True if 'file' matches 'mode'.

    'mode' should be an integer representing an octal mode (eg
    int("755", 8) -> 493).
    """
    # Extract the permissions bits from the file's (or
    # directory's) stat info.
    filemode = stat.S_IMODE(os.stat(file).st_mode)

    return filemode == mode

try:
    top = sys.argv[1]
except IndexError:
    top = '.'

try:
    mode = int(sys.argv[2], 8)
except IndexError:
    mode = MODE

# Convert mode to octal.
mode = int(mode, 8)

for dirpath, dirnames, filenames in os.walk(top):
    dirs = [os.path.join(dirpath, x) for x in dirnames]
    for dirname in dirs:
        if mode_matches(mode, dirname):
            print dirname

Something similar is described in the stdlib documentation for stat.

stat的 stdlib 文档中描述了类似的内容 。

回答by Brian

Take a look at the osmodule. In particular os.statto look at the permission bits.

查看os模块。特别是os.stat查看权限位。

import  os

for filename in os.listdir(dirname):
   path=os.path.join(dirname, filename)
   if os.path.isdir(path):
       if (os.stat(path).st_mode & 0777) == 0775:
           print path

回答by vartec

Compact generator based on Brian's answer:

基于布莱恩的回答的紧凑型发电机:

import os

(fpath for fpath 
   in (os.path.join(dirname,fname) for fname in os.listdir(dirname)) 
   if (os.path.isdir(fpath) and (os.stat(fpath).st_mode & 0777) == 0775))

回答by lithorus

Does it have to be python?

它必须是python吗?

You can also use find to do that :

您也可以使用 find 来做到这一点:

"find . -perm 775"

“找到 .-perm 775”