【问题标题】:Read piped input from other script, while also reading user input, in Python (2.7 and 3.x)在 Python(2.7 和 3.x)中从其他脚本读取管道输入,同时读取用户输入
【发布时间】:2018-10-26 15:49:55
【问题描述】:

我有两个 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

但是,当我尝试从控制台获取输入时,会发生以下情况:

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

关于如何让它发挥作用的任何想法?

【问题讨论】:

    标签: python python-3.x python-2.7 console


    【解决方案1】:

    您已经用尽了标准输入并通过使用 read() 方法到达其文件末尾,该方法读取整个文件流直到 EOF,因此当 input() 想要从同一个文件中读取更多内容时流,它不能,因为文件流已经到达 EOF。

    您应该删除line = sys.stdin.read() 行,因为您实际上只需要用户输入一行,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)
    

    【讨论】:

    • 感谢您的回答!但是,我意识到在我的示例代码中,我实际上并不希望使用从第一个脚本通过管道传输的值,因此此时仅从标准输入中删除读取是不够的。我将编辑我的原始帖子以反映这一点。
    • 标准输入不是这样工作的。标准输入只能来自一个来源。因此,如果您选择将py_a.py 的输出通过管道传输到py_b.py,那么py_b.py 将无法从标准输入中获取用户的输入。
    • 这就解释了为什么很难让它工作,那么:)。我只需要选择其中之一。非常感谢你的帮助!即使我不能做我想做的事,它也为我节省了很多时间来知道这是不可能的。
    • 我已经更新了我的答案,说明在从管道读取标准输入后如何从控制台读取数据。
    猜你喜欢
    • 2015-01-18
    • 2013-11-04
    • 2020-05-24
    • 1970-01-01
    • 2022-12-16
    • 1970-01-01
    • 1970-01-01
    • 2014-03-13
    相关资源
    最近更新 更多