【问题标题】:Python: How can I use GNU readline when the value of sys.stdin has been changed?Python:当 sys.stdin 的值已更改时,如何使用 GNU readline?
【发布时间】:2017-05-13 09:17:19
【问题描述】:

我希望我的 Python 程序从管道获取输入,然后从终端获取输入。在阅读了this SO 的帖子后,我尝试打开 /dev/tty 来替换 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

这种方法的问题是当 sys.stdin != sys.__stdin__ 时 GNU readline 不起作用。我无法使用箭头键移动光标或浏览历史记录。我读到了here 提交的针对这个问题的补丁,但我猜它没有任何结果。

如果有一种方法可以在不更改 sys.stdin 值的情况下同时接受来自管道和终端的输入,我愿意接受建议。

【问题讨论】:

标签: python stdin readline tty


【解决方案1】:

我敢打赌,sys.stdinsys.__stdin__ 并不是你想象的那样。我会在重新分配之前保存原始的 sys.stdin。

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

或者复制一份

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

【讨论】:

    猜你喜欢
    • 2021-06-09
    • 1970-01-01
    • 2017-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多