作为我的 previous question 的延续在 pexpect 中构建交互式选项菜单时,交互输入过滤器中的打印语句只有在交互完成后才会发送到 stdout。
文档似乎没有包含与expect中的send_user等效的方法,是否有任何解决方法可以将输出发送到用户,而不是从pexpect的交互方法中发送到生成的子项?
bash-4.1$ cat testInputFilter.py
import pexpect
def input_filter(s):
if s == b'\003':
print('you pushed ctrl+c')
return b'\r: r u going to kill me? press ctrl-d to exit!\r'
elif s == b'\004':
print('you pushed ctrl+d')
return b'\r: ok, bye; exit\r'
else:
return s
proc = pexpect.spawn('bash --norc')
proc.interact(input_filter=input_filter)
proc.expect(pexpect.EOF)
bash-4.1$ ~/python/python36/bin/python3.6 testInputFilter.py | tee inputTest.txt
bash-4.1$
bash-4.1$ : r u going to kill me? press ctrl-d to exit!
bash-4.1$
bash-4.1$ : ok, bye; exit
exit
you pushed ctrl+c
you pushed ctrl+d
bash-4.1$
最佳答案
真的不知道为什么print()
的数据在与spawned的 child 交互时不会自动刷新,但是你可以显式刷新它,以便实时显示:
print('something')
sys.stdout.flush()
或者直接使用(仅适用于 python3)
# .raw is not buffered
sys.stdout.buffer.raw.write('something')
关于python - pexpect 相当于 Expect 的 "send_user",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49069887/