1

嗨,我正在编写一个伪终端,它可以存在于一个 tty 中并产生第二个 tty,它是过滤输入和输出的

我现在用python写,产生第二个tty,读写很容易

但是当我阅读时,阅读并没有结束,它会等待更多的输入。

import subprocess

pfd = subprocess.Popen(['/bin/sh'], shell=True, 
    stdout=subprocess.PIPE, stdin=subprocess.PIPE)

cmd = "ls" 

pfd.stdin.write(cmd + '\n')

out = ''
while 1: 
    c = pfd.stdout.read(1)
    if not c: # if end of output (this never happends)
        break 
    if c == '\n': # print line when found
        print repr(out)
        out = ''
    else:
        out += c

----------------------------- 输出 -------------------- ----

intty $ python intty.py 
'intty.py'
'testA_blank'
'testB_blank'
(hangs here does not return)

看起来它已经到达 hte 缓冲区的末尾,而不是返回 None 或 '' 它挂起等待更多输入。

我应该寻找什么来查看输出是否已完成?缓冲区结束?一个不可打印的字符?

- - - - - - - - 编辑 - - - - - - -

当我运行 xpcshell 而不是 ls 时也会发生这种情况,我假设这些交互式程序有某种方式知道再次显示提示,奇怪的是提示,在这种情况下“js>”永远不会出现

4

2 回答 2

1

好吧,你的输出实际上还没有完成。因为你 spawned /bin/sh,所以在 "ls" 完成后 shell 仍在运行。没有 EOF 指示器,因为它仍在运行。

为什么不简单地运行/bin/ls

你可以做类似的事情

pfd = subprocess.Popen(['ls'], stdout=subprocess.PIPE, stdin=subprocess.PIPE)

out, err_output = pfd.communicate()

这也突出了subprocess.communicate,这是从单个程序运行中获取输出(无论如何都适合内存的输出)的一种更安全的方法。这只会在程序完成运行时返回。

或者,您可以从 shell 中逐行读取,但您会寻找一个特殊的 shell 序列,例如sh~#可以轻松显示在程序输出中的行。因此,运行 shell 可能是个坏主意。


编辑这是我所指的,但它仍然不是最好的解决方案,因为它有很多警告:

while 1: 
    c = pfd.stdout.read(1)
    if not c:
        break
    elif c == '\n': # print line when found
        print repr(out)
        out = ''
    else:
        out += c
        if out.strip() == 'sh#':
            break

请注意,如果任何其他命令在行首输出“sh#”,并且由于某种原因输出与预期不同,您将进入与以前相同的阻塞情况。这就是为什么它对于外壳来说是一个非常次优的情况。

于 2010-02-17T03:42:15.400 回答
0

对于像 shell 这样的应用程序,在 shell 结束之前输出不会结束。要么用于select.select()检查它是否有更多的输出等着你,要么结束进程。

于 2010-02-17T03:42:03.387 回答