pythoncstdoutfile-descriptorfdopen

Python: how to write to fd 3?


in C, I can write to file descriptor 3 like this:

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

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

Then I can call the program and redirect fd 3 to fd 1 (stdin) like this:

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

How can I do that in python? I checked os.open() but it creates a file descriptor out of a file in the filesystem (apparently I can't select which file descriptor to allocate) and os.fdopen() creates a file object out of a file descriptor (created with os.open()). So, how can I choose the file descriptor number.

I tried:

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

but it gives me:

OSError: [Errno 9] Bad file descriptor

EDIT: This is my python program:

$ cat fd.py
import os

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

And this is the result when I run it:

$ 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.

Solution

  • Change "w+" to "w" in the call to os.fdopen. That's what's causing the "not seekable" error. The + tells it to open it for both reading and writing, which won't work.