#!/usr/bin/env python3 """ Reads a script with a shebang from standard input and executes it. """ import os import subprocess import sys # We are not using sys.stdin because it does internal buffering: # sys.stdin.read(2) can read up to 8192 bytes, we however don't # want that because we want everything after the shebang to be # read by the subprocess. if os.read(0, 2) != b'#!': sys.exit('expected #! shebang') line = b'' while True: byte = os.read(0, 1) if byte == b'': sys.exit('unexpected EOF') if byte == b'\n': break line += byte args = line.strip().split(maxsplit=1) args.append('/dev/stdin') subprocess.run(args) # the subprocess inherits the standard input file # descriptor and interprets the remaining input