I am learning python os
module and faced the issue with os.sendfile(...)
method. Here's my code
import os
f1 = os.open('f1.txt', os.O_RDONLY)
f2 = os.open('f2.txt', os.O_RDWR | os.O_CREAT)
os.sendfile(f2, f1, 0, 100) # <-- Raises OSError: [Errno 38] Socket operation on non-socket
os.close(f1)
os.close(f2)
Python version: 3.9.6 OS: macos monterey (12.6.1)
Here's the link with article that I am trying to follow: https://www.geeksforgeeks.org/python-os-sendfile-method/
What am I doing wrong?
You have to remember that the whole os module is basically just a wrapper for the underlying operation system API. So while the python docs for os.sendfile don't mention anything that would explain your observation, the man page sendfile(2) does:
The sendfile() system call sends a regular file specified by descriptor fd out a stream socket specified by descriptor s.
(emphasis added by me)
So on MacOS (Darwin), sendfile can only be used to send data to a stream socket, not to an arbitrary file descriptor. This is different to Linux, where you can send data to an arbitrary file descriptor. Which may be the reason this isn't mentioned in the python docs.