-
-
Save zmwangx/23806da530a39bb1c0cf to your computer and use it in GitHub Desktop.
Example of how to exhaust stdin from a pipe and then call a function or launch an external program with stdin connected to the tty.
This file contains 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 | |
# Example of how to exhaust stdin from a pipe and then call a function | |
# or launch an external program with stdin connected to the tty. | |
from contextlib import contextmanager | |
import os | |
import subprocess | |
import sys | |
@contextmanager | |
def redirect_stdin(fp): | |
"""Redirect stdin to a file like object or character device. | |
This is a single use context manager. | |
""" | |
saved_stdin = sys.stdin | |
sys.stdin = fp | |
yield | |
sys.stdin = saved_stdin | |
def read_tty(): | |
"""Read a line from tty and echo back what is read.""" | |
sys.stderr.write("Please enter something and press enter.\n") | |
with open('/dev/tty', 'r') as devtty: | |
with redirect_stdin(devtty): | |
line = sys.stdin.readline() | |
print(line) | |
def launch_editor(): | |
"""Launch $EDITOR, or Emacs if $EDITOR is not available.""" | |
with open('/dev/tty', 'r') as devtty: | |
editor = os.environ['EDITOR'] if 'EDITOR' in os.environ else 'emacs' | |
subprocess.call([editor], stdin=devtty) | |
def main(): | |
"""CLI.""" | |
# exhaust stdin first | |
sys.stdin.read() | |
# redirect stdin to tty in a function call | |
read_tty() | |
# redirect stdin to tty when launching an external program | |
launch_editor() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment