I have two Python scripts where I want to pipe the output from the first script, into the second script, while also being able to read user input from console in the second script.
This is very simplified example code, to give an idea of what I'm trying to do:
py_a.py
print(1+2)
py_b.py
import sys
invalue = sys.stdin.read()
print("value from py_a is " + invalue)
answer = input("Talk to me! ")
# do something with answer
And in terminal I wish to do something like python py_a.py | python py_b.py
python py_a.py | python py_b.py
However, when I try to get input from console, the following happen:
Talk to me! Traceback (most recent call last):
File "py_b.py", line 3, in <module>
answer = input("Talk to me! ")
EOFError: EOF when reading a line
Any ideas on how I can get this to work?
You've already exhausted the standard input and reached its end-of-file by using the read()
method, which reads the entire file stream until the EOF, so when input()
wants to read more from the same file stream, it can't because the file stream has already reached EOF.
You should remove the line line = sys.stdin.read()
since you really just want one line of input from the user, which the input()
function will do.
EDIT: If you want py_b.py
to be able to read from the console after reading standard input piped from py_a.py
, you can install the keyboard
module to read directly from the user's keyboard instead:
import keyboard
import time
class InputHandler:
def __init__(self):
self.buffer = ''
def on_press(self, event):
if event.name == 'enter':
self.do_something()
self.buffer = ''
elif event.name == 'backspace':
self.buffer = self.buffer[:-1]
else:
self.buffer += event.name
def do_something(self):
global running
if self.buffer == 'exit':
running = False
print('You entered: ' + self.buffer)
invalue = sys.stdin.read()
print("value from py_a is " + invalue)
keyboard.on_press(InputHandler().on_press)
running = True
while running:
time.sleep(1)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.