Python pexpect模块交互方法筛选器

Python pexpect模块交互方法筛选器,python,filter,pexpect,Python,Filter,Pexpect,我是Python的新手,我正在尝试使用pexpect,对interact的输入/输出过滤器感兴趣。但我不知道如何使用过滤器 在Pexpect的文档中,关于interact方法,提到: 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 ke

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

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

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”,我该如何做?(过滤器应该是什么?)


提前感谢。

当pexpect从底层文件描述符读取输入/输出块时,会将其传递给每个输入/输出块。这可能是从一个字节到1000字节的任意位置,具体取决于发生的情况

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


谢谢你,托马斯。“def过滤器(输入):“工作正常。我假设“input”是Python的内置函数。但是,如果我还想添加一个输出过滤器,可以说“def out_filter(??)”,而不是“input”,那么我应该为占位符“?”使用什么呢。似乎没有内置函数“output”。
input
这里只是我选择的一个名称,而不是Python内置函数。覆盖一个内置变量有点淘气——我对变量命名很懒惰。可以随意调用它,例如,
chunk
@ThomasK是否也可以基于特定输入发送转义字符并退出交互模式?例如,如果用户在交互模式下键入“是”,我想退出该模式。请帮忙
def my_input(str):
    return str + "aaa"
...
...
c.interact(input_filter=?)
def filter(input):
    return input.replace(b'\r\n', b'aaa\r\n')

c.interact(input_filter=filter)