Python: How can I use readline for GNU when the sys.stdin value has been changed?

I want my Python program to accept input from a pipe and later receive input from a terminal. After reading this SO post, I tried opening / dev / tty to replace sys.stdin.

import sys import readline def tty_input(prompt): with open("/dev/tty") as terminal: sys.stdin = terminal user_input = input(prompt) sys.stdin = sys.__stdin__ return user_input 

The problem with this approach is that GNL readline does not work when sys.stdin! = Sys .__ stdin__. I cannot use the arrow keys to move the cursor or navigate the history. I read the patch for this very question that was presented here , but I assume that none of this came out.

If there is a way to accept input from both the pipe and the terminal without changing the sys.stdin value, I am open to suggestions.

+5
source share
1 answer

I am sure sys.stdin and sys.__stdin__ not what you think. I would save the original sys.stdin file before reassigning it.

 import sys import readline def tty_input(prompt): oldStdin = sys.stdin with open("/dev/tty") as terminal: sys.stdin = terminal user_input = input(prompt) sys.stdin = oldStdin return user_input 

Or make a copy

 import sys import readline import copy def tty_input(prompt): oldStdin = copy.copy(sys.stdin) with open("/dev/tty") as terminal: sys.stdin = terminal user_input = input(prompt) sys.stdin = oldStdin return user_input 
0
source

Source: https://habr.com/ru/post/1262010/


All Articles