2

如果文件尚不存在,我正在尝试创建和写入文件,以便在竞争条件下合作安全,并且我遇到了(可能是愚蠢的)问题。首先,这是代码:

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 进行测试的。如果您尝试该代码并且它适用于您,请在您的环境中写下评论。

至少安全地做同样事情的替代代码也是非常受欢迎的。

4

2 回答 2

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)
于 2013-04-03T15:24:45.797 回答
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.
于 2013-04-03T15:29:59.723 回答