gpt4 book ai didi

python - 如何使用默认权限使用 Python 创建目录?

转载 作者:太空宇宙 更新时间:2023-11-04 07:10:42 35 4
gpt4 key购买 nike

我想使用与 shell 的 mkdir 相同的权限在 Python 中创建一个目录。

standard Python documentation说:

os.mkdir(path[, mode])

Create a directory named path with numeric mode mode. The default mode is 0777 (octal). On some systems, mode is ignored. Where it is used, the current umask value is first masked out. If the directory already exists, OSError is raised.

我不想要默认的 0777 权限,而是从父目录继承的权限。我可以在不查询父目录权限的情况下执行此操作吗?

最佳答案

您已经获得了与 shell 的 mkdir 相同的权限。

带壳mkdir :

For each dir operand, the mkdir utility shall perform actions equivalent to the mkdir() function defined in the System Interfaces volume of IEEE Std 1003.1-2001, called with the following arguments:

The dir operand is used as the path argument.

The value of the bitwise-inclusive OR of S_IRWXU, S_IRWXG, and S_IRWXO is used as the mode argument. (If the -m option is specified, the mode option-argument overrides this default.)

或者,更易读(来自 BSD 联机帮助页):

... creates the directories named as operands, in the order specified, using mode rwxrwxrwx (0777) as modified by the current umask(2).

Python 的 os.mkdir 做完全相同的事情:

... [t]he default mode is 0777... the current umask value is first masked out.

Python 实际上调用了完全相同的 POSIX mkdir shell 文档中提到的具有完全相同参数的函数。该函数定义为:

The file permission bits of the new directory shall be initialized from mode. These file permission bits of the mode argument shall be modified by the process' file creation mask.

或者,更易读,来自 FreeBSD/OS X 联机帮助页:

The directory path is created with the access permissions specified by mode and restricted by the umask(2) of the calling process.

如果您在 Windows 等非 POSIX 平台上,Python 会尝试模拟 POSIX 行为,即使 native shell 有一个名为 mkdir 的命令以不同方式工作。这主要是因为主要的此类 shell 是 Windows,它有一个 mkdir,它是 md 的同义词。 ,甚至没有记录它在权限方面所做工作的详细信息。

关于python - 如何使用默认权限使用 Python 创建目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12466190/

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