File: gobble.py 1 #!/usr/bin/python3 2 3 # The MIT License (MIT) 4 # 5 # Copyright © 2020-2025 pacman64 6 # 7 # Permission is hereby granted, free of charge, to any person obtaining a copy 8 # of this software and associated documentation files (the “Software”), to deal 9 # in the Software without restriction, including without limitation the rights 10 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 11 # copies of the Software, and to permit persons to whom the Software is 12 # furnished to do so, subject to the following conditions: 13 # 14 # The above copyright notice and this permission notice shall be included in 15 # all copies or substantial portions of the Software. 16 # 17 # THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 18 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 19 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 20 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 21 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 22 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 23 # SOFTWARE. 24 25 26 from io import BytesIO 27 from os import close, pipe, write 28 from subprocess import call 29 from sys import argv, exit, stderr, stdin, stdout 30 31 32 info = ''' 33 gobble [command...] [args...] 34 35 Read all bytes from standard input, and only then emit them out, or run 36 the command given, sending those bytes to its standard input. 37 ''' 38 39 40 if len(argv) > 1 and argv[1] in ('-h', '--h', '-help', '--help'): 41 print(info.strip()) 42 exit(0) 43 44 45 try: 46 if len(argv) > 1: 47 r, w = pipe() 48 data = stdin.buffer.read() 49 # os.write always hangs when given more than a few kilobytes 50 chunk_size = 4 * 1024 51 while len(data) >= chunk_size: 52 write(w, data[:chunk_size]) 53 data = data[chunk_size:] 54 write(w, data) 55 close(w) 56 exit(call(argv[1:], stdin=r, stdout=stdout, stderr=stderr)) 57 else: 58 stdout.buffer.write(stdin.buffer.read()) 59 except BrokenPipeError: 60 stderr.close() 61 exit(0) 62 except KeyboardInterrupt: 63 exit(2) 64 except Exception as e: 65 print(f'\x1b[31m{e}\x1b[0m', file=stderr) 66 exit(1)