Last active
October 24, 2024 18:21
-
-
Save eddieantonio/71b12f20eecfaba02c56aa977040a1ee to your computer and use it in GitHub Desktop.
An example of reopening the controlling terminal when stdin is attached to a pipe.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
""" | |
An example of re-opening stdin. Lets you pipe input to a program and still interact with | |
the program via stdin. | |
Example: | |
$ seq 5 | ./reopen-stdin.py | |
Type a prefix: #=> | |
#=> 1 | |
#=> 2 | |
#=> 3 | |
#=> 4 | |
#=> 5 | |
""" | |
import os | |
import sys | |
# Duplicate the stdin's file descriptor: | |
# (You probably want to check whether stdin is a tty first) | |
pipe_in_fd = os.dup(sys.stdin.fileno()) | |
pipe_in = os.fdopen(pipe_in_fd, "rt") | |
# Okay, we're done with the pipe: | |
sys.stdin.close() | |
# Re-open the controlling terminal using /dev/tty. | |
# See https://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap10.html | |
sys.stdin = open("/dev/tty", "rt") | |
# Getting input from (the new) stdin: | |
prefix = input("Type a prefix: ").strip() | |
for line in pipe_in: | |
print(prefix, line, end="") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment