summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMartin Fischer <martin@push-f.com>2021-11-28 18:55:19 +0100
committerMartin Fischer <martin@push-f.com>2021-11-28 20:35:56 +0100
commitc629c3a0f01b7b5ccaacf7fb85df10ae5d59de9b (patch)
tree7388fe044e2495b9dfe94ec76d7ffbdf4747caa7
parent40690d6e1f87fe73bdc999b48c0caa05499396eb (diff)
add shebang
-rwxr-xr-xshebang32
1 files changed, 32 insertions, 0 deletions
diff --git a/shebang b/shebang
new file mode 100755
index 0000000..09ecd76
--- /dev/null
+++ b/shebang
@@ -0,0 +1,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