summaryrefslogtreecommitdiff
path: root/shebang
blob: 09ecd76d89bce61046c64272d77f93fa1a7d3999 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#!/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