#!/usr/bin/python3 # The MIT License (MIT) # # Copyright © 2020-2025 pacman64 # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the “Software”), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from io import BytesIO from os import close, pipe, write from subprocess import call from sys import argv, exit, stderr, stdin, stdout info = ''' gobble [command...] [args...] Read all bytes from standard input, and only then emit them out, or run the command given, sending those bytes to its standard input. ''' if len(argv) > 1 and argv[1] in ('-h', '--h', '-help', '--help'): print(info.strip()) exit(0) try: if len(argv) > 1: r, w = pipe() data = stdin.buffer.read() # os.write always hangs when given more than a few kilobytes chunk_size = 4 * 1024 while len(data) >= chunk_size: write(w, data[:chunk_size]) data = data[chunk_size:] write(w, data) close(w) exit(call(argv[1:], stdin=r, stdout=stdout, stderr=stderr)) else: stdout.buffer.write(stdin.buffer.read()) except BrokenPipeError: stderr.close() exit(0) except KeyboardInterrupt: exit(2) except Exception as e: print(f'\x1b[31m{e}\x1b[0m', file=stderr) exit(1)