Python pexpect模块interact方法过滤器
我刚开始学Python,想用pexpect这个库,特别对它的交互功能中的输入/输出过滤器感兴趣。但是我搞不清楚这个过滤器该怎么用。
在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”,我该怎么做呢?(这个过滤器应该是什么样的?)
def my_input(str):
return str + "aaa"
...
...
c.interact(input_filter=?)
提前谢谢你们。
1 个回答
1
每次输入或输出的数据块都是由pexpect从底层文件描述符读取的。这些数据块的大小可能从一个字节到1000个字节不等,这取决于具体情况。
如果你想在每行的末尾添加一些内容,你需要写一个函数来检查换行符。可以参考下面这个示例(未经测试):
def filter(input):
return input.replace(b'\r\n', b'aaa\r\n')
c.interact(input_filter=filter)