相当于send_user / Expect_user的对象

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

[我想将我从expect编写的程序转换为pexpect,但是api根本不同,并且我从expect知道和喜欢的许多功能还没有弄清楚如何在python

我想知道是否有人可以与用户进行纯粹的交互。期望我将send_userexpect_user配对使用,这种类型的序列通常是由生成的过程中观察到的模式触发的,或者是由与生成的过程进行交互时使用的特殊键代码触发的。

[我看到了thissend_user示例,并试图在输入提示后打印python input()函数,但我的程序锁定了。

这里是代码段:

import pexpect
import sys

def input_filter(s):
    if s == b'\004': # ctrl-d
        sys.stdout.write(f'\n\rYou pressed ctrl-d, press y to quit.\r\n')
        sys.stdout.flush()
        i = input()
        if i == 'y':
            return b'\r: ok, bye; exit\r'
        else:
            return b''
    else:
        return s

proc = pexpect.spawn('bash --norc')
proc.interact(input_filter=input_filter)
python expect pexpect
1个回答
2
投票

input()内调用input_filter()无效。您需要使interact()返回并根据需要重新输入。

请参见以下示例:

[STEP 104] # cat interact.py
#!/usr/bin/env python3

import pexpect, sys

got_ctrl_d = False
def input_filter(s):
    global got_ctrl_d

    if s == b'\x04':
        got_ctrl_d = True
        # \x1d (CTRL-]) is the default escape char
        return b'\x1d'
    else:
        return s

proc = pexpect.spawn('bash --norc')

while True:
    got_ctrl_d = False
    proc.interact(input_filter=input_filter)
    if got_ctrl_d:
        sys.stdout.write('\nAre you sure to exit? [y/n] ')
        inp = input()

        if inp == 'y':
            proc.sendline('exit')
            break
        else:
            # press ENTER so we can see the next prompt
            proc.send('\r')
    else:
        break

proc.expect(pexpect.EOF)

尝试:

[STEP 105] # python3 interact.py
bash-5.0#                         <-- press CTRL-D
Are you sure to exit? [y/n] n     <-- input 'n' and press ENTER

bash-5.0#                         <-- press CTRL-D
Are you sure to exit? [y/n] y     <-- input 'y' and press ENTER
[STEP 106] #
© www.soinside.com 2019 - 2024. All rights reserved.