Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如果数据通过管道传输到我的程序,Python诅咒getch()总是返回-1_Python_Python 3.x_Python Curses - Fatal编程技术网

如果数据通过管道传输到我的程序,Python诅咒getch()总是返回-1

如果数据通过管道传输到我的程序,Python诅咒getch()总是返回-1,python,python-3.x,python-curses,Python,Python 3.x,Python Curses,我想读取通过管道传输到程序中的数据,然后使用诅咒接受用户输入。我有以下代码: import curses import sys import select def read_piped_data(): data = "" while(sys.stdin in select.select([sys.stdin,],[],[],0.0)[0]): x = sys.stdin.read(1) if(len(x) == 0): bre

我想读取通过管道传输到程序中的数据,然后使用诅咒接受用户输入。我有以下代码:

import curses
import sys
import select

def read_piped_data():
    data = ""
    while(sys.stdin in select.select([sys.stdin,],[],[],0.0)[0]):
        x = sys.stdin.read(1)
        if(len(x) == 0): break
        data += x
    sys.stdin = open("/dev/tty")
    return (data if len(data) > 0 else None)

def main(stdscr):
    data = read_piped_data()
    if(data != None): do_something1(data)
    curses.raw()
    stdscr.keypad(True)
    stdscr.timeout(0)

    while(True):
        ch = stdscr.getch()
        if(ch == -1): continue
        if(not do_something2(stdscr,ch)): break

curses.wrapper(main)
当我使用以下命令执行上述操作时:

$ python3 test.py
一切都很完美:
do\u something 1()
不被调用,但每当我按下任何键时都会调用
do\u something 2()
。但当我把某件事说成:

$ ls | python3 test.py
我的代码失败:
do\u something1()
被调用,它正确地处理管道数据,但
do\u something2()
从未被调用,我的程序基本上处于无限循环中,没有注册任何按键

保持或删除sys.stdin=open(“/dev/tty”)无效。在另一个stackoverflow回答中,我发现这个解决方案可以使input()工作(在从管道读取之后)。虽然input()在我重新分配stdin后可以工作,但getch()不能

即使我不读取管道传输的数据,只要将一些命令传输到我的程序就足以搞乱阻止它读取任何按键的诅咒getch()


我在Ubuntu 20.04上使用Python3.8的诅咒。从管道读取数据后,如何在curses中“重新激活”输入?

可能是因为stdin不保证可分配? 在C,我对此没有问题:

freopen("/dev/tty","r",stdin);

使用fopen重新分配也在这里起作用。

如果
select
循环超出输入,则循环停止,即使以后可能会有更多输入。这听起来不是正确的做法。即使你是对的:在我的特殊情况下(使用“ls”示例),整个管道输出都得到了正确的处理。我的问题是getch()。即使我选择根本不读取管道数据,只要将某个命令的输出管道化到我的程序就足以让我的诅咒getch()无法读取任何内容!重新分配
sys.stdin
不会更改程序的实际stdin。您可能需要处理文件描述符和
os.dup2
。我认为有python等价物。我不知道。