相当于send_user / Expect_user的pexpect

我想将我从expect编写的程序转换为pexpect,但是api根本不同,而且我还没有从expect中学到并喜欢的许多功能t在python中找到了用法。

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

我看到了send_user的{​​{3}}示例,并尝试打印一个提示输入的信息,随后是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)
fudandownload 回答:相当于send_user / Expect_user的pexpect

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] #
本文链接:https://www.f2er.com/2878790.html

大家都在问