Python 3.3+Linux · macOSosfunction
os.sendfile
os — efficient copying
Copy data between descriptors in the kernel, without a user-space buffer. Availability: Unix.
Syntax
os.sendfile(...)
Data never passes through Python's memory, which is why it serves files to sockets so quickly — socket.sendfile is built on it. It may transfer less than requested and returns the bytes sent. The signature and the allowed descriptor types differ between Linux and macOS, so portable code is better off with the higher-level socket.sendfile.
Examples
import os
src = os.open('send_src.txt', os.O_RDWR | os.O_CREAT | os.O_TRUNC) # временный файл-источник
print(os.write(src, b'hello world!')) # → 12 — подготовили 12 байт данных
dst = os.open('send_dst.txt', os.O_WRONLY | os.O_CREAT | os.O_TRUNC) # приёмник; на практике сюда подставляют дескриптор сокета
print(os.sendfile(dst, src, 0, 5)) # → 5 — ядро переслало b'hello' с нулевого смещения, минуя память процесса
print(os.sendfile(dst, src, 5, 100)) # → 7 — отправлен остаток файла, count можно брать с запасом
print(os.sendfile(dst, src, 12, 10)) # → 0 — смещение за концом файла, отправлять нечего
See also
Open in the full glossarydocs.python.orgReport an inaccuracy