这个问题与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中的已知错误?
提前致谢!
答案 0 :(得分:8)
您必须选择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()
/ { {1}},然后在引发异常之前检查文件描述符上的标志(F_GETFL)。)
答案 1 :(得分:2)
非常时髦。
os.fdopen(os.open("a1", os.O_CREAT | os.O_RDWR | os.O_APPEND | os.O_EXCL))
有效,而
os.fdopen(os.open("a1", os.O_CREAT | os.O_WRONLY | os.O_APPEND | os.O_EXCL))
将OSError: [Errno 22] Invalid argument
提升为os.fdopen()
。
因此os.fdopen()需要对FD进行完全读/写访问。除非你做
os.fdopen(fd, "w")
,与只写文件一起使用。