gpt4 book ai didi

python - Python 中的 "chmod -R u+x $path"是什么?

转载 作者:行者123 更新时间:2023-12-04 17:08:22 25 4
gpt4 key购买 nike

这个 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.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")

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

关于python - Python 中的 "chmod -R u+x $path"是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70021645/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com