pexpect相当于Expect的“send_user”

问题描述 投票:0回答:1

作为我的previous question在pexpect中构建交互式选项菜单的延续,交互式输入过滤器中的print语句在交互完成之前不会被发送到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$
python expect pexpect
1个回答
1
投票

不知道为什么print()的数据在与衍生的孩子交互时不会自动刷新,但是你可以明确地刷新它以便实时显示:

print('something')
sys.stdout.flush()

或者只是使用(仅适用于python3)

# .raw is not buffered
sys.stdout.buffer.raw.write('something')
© www.soinside.com 2019 - 2024. All rights reserved.