嗨,我正在写一个psudo-terminal,它可以存在于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 += cintty $ python intty.py
'intty.py'
'testA_blank'
'testB_blank'
(hangs here does not return)它看起来正在到达缓冲区的末尾,而不是返回None或'‘,而是挂起等待更多的输入。
要查看输出是否已完成,我应该查找什么?缓冲区的末尾?一个不可打印的字符?
-编辑
当我运行xpcshell而不是ls时,这种情况也会发生,我假设这些交互式程序有某种方法知道再次显示提示符,奇怪的是提示符,在本例中"js>“从不出现
发布于 2010-02-17 11:42:15
好吧,你的输出实际上还没有完成。因为您生成了/bin/sh,所以shell在"ls“完成后仍在运行。没有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#‘,并且由于某种原因输出与预期的不同,则会出现这种情况,您将进入与之前相同的阻塞情况。这就是为什么对于shell来说,这是一种非常不理想的情况。
发布于 2010-02-17 11:42:03
对于像shell这样的应用程序,输出直到shell结束才会结束。要么使用select.select()检查是否有更多的输出等待您,要么结束该过程。
https://stackoverflow.com/questions/2278150
复制相似问题