这个问题与 Write file with specific permissions in Python 的答案有关用于打开具有特定权限的写入文件(在 python 中)。
答案中的代码如下所示:
with os.fdopen(os.open('foo', os.O_APPEND | os.O_CREAT, 0o644)) as out:
out.write("hello\n")
2.7.1 中的这段代码(我公司没有安装 2.7.3)产生:
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
IOError: File not open for writing
os.fdopen
有自己的模式参数,但设置没有帮助:
>>> with os.fdopen(os.open('foo', os.O_APPEND | os.O_CREAT, 0o644), 'a') as out:
... out.write("hello\n")
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OSError: [Errno 22] Invalid argument
长话短说,我无法弄清楚如何实际写入已通过 os.fdopen
和 os.open
打开的文件。有任何想法吗? 2.7.1 中的已知错误?
提前致谢!
最佳答案
您必须选择 O_RDONLY、O_WRONLY 或 O_RDWR 之一作为 open() 的“基本”模式参数。
您没有明确地这样做,因此假定为 O_RDONLY(在许多系统上为零)。 Python 的 os.fdopen
看到您指定了一个 O_RDONLY 和 O_APPEND,这有点傻。 Python 提示这种组合与您看到的 EINVAL(“无效参数”)错误。
(事实上,如果您 strace(1)
您的脚本 — 我假设这里是 Linux — 我怀疑您会看到没有遇到“自然的” EINVAL。相反,python 执行您的 os.open()
/open(2)
,然后在引发异常之前检查文件描述符上的标志 (F_GETFL)。)
关于python os.fdopen(os.open()) 不能用来写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13257748/