gpt4 book ai didi

Python pexpect 模块交互方法过滤器

转载 作者:太空宇宙 更新时间:2023-11-03 18:26:07 25 4
gpt4 key购买 nike

我是Python新手,我正在尝试使用pexpect,对interact的输入/输出过滤器感兴趣。但我不知道如何使用过滤器。

在Pexpect的文档中,关于交互方法,提到:

interact(escape_character=’x1d’, input_filter=None, output_filter=None)

This gives control of the child process to the interactive user (the human at
the keyboard). Keystrokes are sent to the child process, and the stdout and stderr
output of the child process is printed. This simply echos the child stdout and child
stderr to the real stdout and it echos the real stdin to the child stdin. When the
user types the escape_character this method will stop. The default for
escape_character is ^]. This should not be confused with ASCII 27 – the ESC
character. ASCII 29 was
chosen for historical merit because this is the character used by ‘telnet’ as the
escape character. The escape_character will not be sent to the child process.

You may pass in optional input and output filter functions. These functions should
take a string and return a string. The output_filter will be passed all the output
from the child process. The input_filter will be passed all the keyboard input from
the user. The input_filter is run BEFORE the check for the escape_character.

但是没有任何示例如何使用输入或输出过滤器。唯一的就是它提到的是,“这些函数应该接受一个字符串并返回一个字符串”。

例如,如果我想在每个用户输入中附加“aaa”,我该怎么做? (过滤器应该是什么?)

def my_input(str):
return str + "aaa"
...
...
c.interact(input_filter=?)

提前致谢。

最佳答案

当 pexpect 从底层文件描述符中读取输入/输出的每个 block 时,它会被传递。这可能是从单个字节到 1000 个字节的任何位置,具体取决于发生的情况。

如果您想在每行末尾添加一些内容,您需要编写一个检查换行符的函数。像这样的东西(未经测试):

def filter(input):
return input.replace(b'\r\n', b'aaa\r\n')

c.interact(input_filter=filter)

关于Python pexpect 模块交互方法过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23170847/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com