3

在 C 中,我可以像这样写入文件描述符 3:

$ cat write.c 
#include <unistd.h>

int main(void) {
    write(3, "written in fd 3\n", 16);
}

然后我可以调用程序并将 fd 3 重定向到 fd 1 (stdin),如下所示:

$ ./write 3>&1
written in fd 3

我怎么能在python中做到这一点?我检查了os.open(),但它从文件系统中的文件创建文件描述符(显然我无法选择要分配的文件描述符)并os.fdopen()从文件描述符(使用创建os.open())创建文件对象。那么,我该如何选择文件描述符编号。

我试过了:

with os.fdopen(3, 'w+') as fdfile:

但它给了我:

OSError: [Errno 9] Bad file descriptor

编辑:这是我的 python 程序:

$ cat fd.py
import os

with os.fdopen(3, 'w+') as fdfile:
    fdfile.write("written to fd 3\n")
    fdfile.close()

这是我运行它时的结果:

$ python fd.py 3>&1
Traceback (most recent call last):
  File "fd.py", line 3, in <module>
    with os.fdopen(3, 'w+') as fdfile:
  File "/usr/lib/python3.8/os.py", line 1023, in fdopen
    return io.open(fd, *args, **kwargs)
io.UnsupportedOperation: File or stream is not seekable.
4

2 回答 2

1

在对 的调用中更改"w+"为。这就是导致“不可搜索”错误的原因。告诉它打开它以进行阅读和写作,这是行不通的。"w"os.fdopen+

于 2020-05-01T03:01:08.743 回答
1

您的代码应该可以工作。但就像在运行 C 程序时一样,您必须先重定向 FD 3。

python write.py 3>&1
于 2020-05-01T02:20:54.177 回答