我是Python的新手,我正在尝试使用pexpect,对交互的输入/输出过滤器感兴趣。但我无法弄清楚如何使用过滤器。
关于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=?)
提前致谢。
答案 0 :(得分:1)
当pexpect从底层文件描述符中读取它时,传递每个输入/输出块。这可能是从单个字节到1000个字节的任何位置,具体取决于正在进行的操作。
如果要在每行的末尾添加内容,则需要编写一个检查换行符的函数。像这样(未经测试):
def filter(input):
return input.replace(b'\r\n', b'aaa\r\n')
c.interact(input_filter=filter)