簡體   English   中英

在Python(2.7和3.x)中讀取其他腳本的管道輸入,同時還讀取用戶輸入

[英]Read piped input from other script, while also reading user input, in Python (2.7 and 3.x)

我有兩個Python腳本,我想將第一個腳本的輸出傳遞到第二個腳本,同時還能夠從第二個腳本的控制台讀取用戶輸入。

這是非常簡化的示例代碼,可以讓我大致了解一下:

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

在終端中,我希望執行類似python py_a.py | python py_b.py python py_a.py | python py_b.py

但是,當我嘗試從控制台獲取輸入時,會發生以下情況:

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

關於如何使它起作用的任何想法?

您已經用完read()方法耗盡了標准輸入並到達了文件結尾,該方法會讀取整個文件流直到EOF,因此當input()要從同一文件流中讀取更多內容時,不能,因為文件流已經達到EOF。

您應該刪除line = sys.stdin.read()行,因為您實際上只希望從用戶那里input()一行,而input()函數會這樣做。

編輯:如果希望py_b.py在讀取從py_a.py標准輸入后能夠從控制台讀取,則可以安裝keyboard模塊以直接從用戶的鍵盤讀取:

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM