Skip to content

Instantly share code, notes, and snippets.

@heiner
Last active June 21, 2022 19:10
Show Gist options
  • Save heiner/4733ac831b50321ab6a33002bdbef8d3 to your computer and use it in GitHub Desktop.
Save heiner/4733ac831b50321ab6a33002bdbef8d3 to your computer and use it in GitHub Desktop.
import os
import sys
import ctypes
ld = ctypes.CDLL(None, use_errno=True)
SPLICE_F_NONBLOCK = getattr(os, "SPLICE_F_NONBLOCK", 0x02)
def tee(fd_in, fd_out, length, flags=SPLICE_F_NONBLOCK):
result = ld.tee(
ctypes.c_int(fd_in),
ctypes.c_int(fd_out),
ctypes.c_size_t(length),
ctypes.c_uint(flags),
)
if result == -1:
errno = ctypes.get_errno()
raise OSError(errno, os.strerror(errno))
return result
def main():
stdin = sys.stdin.fileno()
stdout = sys.stdout.fileno()
with open("tee.out", "wb") as f:
while True:
length = tee(stdin, stdout, 1 << 31)
if not length:
break
# In Python 3.10, could use os.splice. See tee(2).
buf = sys.stdin.buffer.read(length)
f.write(buf)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment