如果有的话,我需要做什么来关闭从 os.open
获得并随后与 with os.fdopen
一起使用的文件描述符?我从下面的代码中得到的 OSError
让我认为答案可能是“无”,但我无法在文档中找到确认信息。
fd = os.open(os.path.expanduser("~/Desktop/foo"), os.O_WRONLY)
with os.fdopen(fd, "wt") as file:
pass
os.close(fd) # OSError: [Errno 9] Bad file descriptor
最佳答案
在 Python 2 中,通常在 Python 3 中,文件使用 fdopen
打开,C 标准 IO 拥有文件描述符。当使用 fclose
关闭文件时,底层描述符也将关闭。因此,文件在 with
block 的末尾关闭。
fdopen
(3) 上的 Linux 手册说
The fdopen() function associates a stream with the existing file descriptor, fd. The mode of the stream (one of the values "r", "r+", "w", "w+", "a", "a+") must be compatible with the mode of the file descriptor. The file position indicator of the new stream is set to that belonging to fd, and the error and end-of-file indicators are cleared. Modes "w" or "w+" do not cause truncation of the file. The file descriptor is not dup'ed, and will be closed when the stream created by fdopen() is closed. The result of applying fdopen() to a shared memory object is undefined.
在 Python 3 中 os.fdopen
是 open
的包装器/几乎是别名内置函数:
os.fdopen(fd, *args, **kwargs)
Return an open file object connected to the file descriptor
fd
. This is an alias of theopen()
built-in function and accepts the same arguments. The only difference is that the first argument offdopen()
must always be an integer.
open
文档在打开文件描述符时是这样说的:
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
Open file and return a corresponding file object. If the file cannot be opened, an OSError is raised.
file is either a string or bytes object giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. (If a file descriptor is given, it is closed when the returned I/O object is closed, unless closefd is set to False.)
因此,如果您想在 Python 文件对象关闭时保持文件描述符打开,您可以这样做
fd = os.open(os.path.expanduser("~/Desktop/foo"), os.O_WRONLY)
with os.fdopen(fd, "wt", closefd=False) as file:
pass
# I/O object dissociated but fd valid
os.close(fd) # no error.
关于python - 关闭我在 fdopen 中使用的文件描述符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24984887/