在Python中使用os.open时出错

时间:2013-04-03 15:14:04

标签: python file-io atomic

我正在尝试创建并编写一个文件,如果它还不存在,那么它在竞争条件下是合作安全的,而且我有(可能是愚蠢的)问题。首先,这是代码:

import os

def safewrite(text, filename):
    print "Going to open", filename
    fd = os.open(filename, os.O_CREAT | os.O_EXCL, 0666) ##### problem line?
    print "Going to write after opening fd", fd
    os.write(fd, text)
    print "Going to close after writing", text
    os.close(fd)
    print "Going to return after closing"

#test code to verify file writing works otherwise
f = open("foo2.txt", "w")
f.write("foo\n");
f.close()
f = open("foo2.txt", "r")
print "First write contents:", f.read()
f.close()
os.remove("foo2.txt")

#call the problem method
safewrite ("test\n", "foo2.txt")

然后问题,我得到例外:

First write contents: foo

Going to open foo2.txt
Going to write after opening fd 5

Traceback (most recent call last):
  File "/home/user/test.py", line 21, in <module>
    safewrite ("test\n", "foo2.txt")
  File "/home/user/test.py", line 7, in safewrite
    os.write(fd, text)
OSError: [Errno 9] Bad file descriptor

上面的代码中标出了可能的问题行(我的意思是,它还能做什么?),但我无法弄清楚如何修复它。有什么问题?

注意:上面是在Linux VM中使用Python 2.7.3进行测试的。如果您尝试使用该代码并且它适用于您,请在您的环境中撰写评论。

替代代码至少同样安全也非常受欢迎。

2 个答案:

答案 0 :(得分:9)

更改行:

fd = os.open(filename, os.O_CREAT | os.O_EXCL, 0666)

代替:

fd=os.open(filename, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0666)

答案 1 :(得分:2)

您必须使用一个标志打开该文件,以便您可以写入该文件(os.O_WRONLY)。

来自open(2)

DESCRIPTION
       The argument flags must include one of the following access modes: O_RDONLY, O_WRONLY, or O_RDWR.   These  request  opening  the  file  read-only,
       write-only, or read/write, respectively.

来自write(2)

NAME
       write - write to a file descriptor

...    
ERRORS
       EAGAIN The file descriptor fd has been marked non-blocking (O_NONBLOCK) and the write would block.

       EBADF  fd is not a valid file descriptor or is not open for writing.