【问题标题】:What is the equivalent of "chmod -R u+x $path" in Python?Python中的“chmod -R u+x $path”等价于什么?
【发布时间】:2021-12-29 10:46:37
【问题描述】:

这个 bash 命令在 Python 中的等价物是什么?

chmod -R u+x $dir_path

os.fchmod,但不确定它是否像原始命令一样递归应用。

这和我想要的一样吗?

import os
import stat
from pathlib import Path

fd = Path(dir_path).open().fileno()
os.fchmod(fd, stat.S_IXUSR)

【问题讨论】:

  • 可能是 os.walk(path) 然后 os.chmod() 每个文件单独。无需使用需要文件句柄的os.fchmod(fd) 变体。当然,你总是可以使用os.system() 来运行chmod。
  • @Demi-Lune 几乎相同,尽管这个问题与文件所有权有关。

标签: python bash


【解决方案1】:

您可以使用os.chmod,但这只会更改单个文件或目录的权限。要增量更改单个文件的权限(通过添加到现有权限),请使用:

import os
import stat

st = os.stat("path/to/file")
os.chmod("/path/to/file", st.st_mode | stat.S_IXUSR)

现在,要递归更改目录中文件的权限,您需要使用os.walk 遍历所有子目录及其文件:

import os
import stat

for root, dirs, files in os.walk("path/to/directory"):
    for name in dirs:
        path = os.path.join(root, name)
        st = os.stat(path)
        os.chmod(path, st.st_mode | stat.S_IXUSR)
    for name in files:
        path = os.path.join(root, name)
        st = os.stat(path)
        os.chmod(path, st.st_mode | stat.S_IXUSR)

上面既会遍历子目录,也会增量修改权限,只增加用户执行权限。

还有其他选择,一个有趣且显而易见的选择是:

os.system("chmod -R u+x /path/to/file")

为了将来参考,这里有两个相关的问题:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-21
    • 2020-02-25
    • 2013-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-31
    • 2015-04-18
    相关资源
    最近更新 更多