我正在尝试制作一个程序,该程序以可执行文件名作为参数,运行可执行文件并报告该运行的输入和输出。例如,考虑一个名为“ circle”的子程序。我的程序需要运行以下内容:
$ python3 capture_io.py ./circle Enter radius of circle: 10 Area: 314.158997 [('output', 'Enter radius of circle: '), ('input', '10\n'), ('output', 'Area: 314.158997\n')]
我决定为此工作使用pexpect
模块。它具有一种称为interact
的方法,该方法使用户可以与子程序进行交互,如上所示。它还具有2个可选参数:output_filter
和input_filter
。从文档中:
output_filter
将传递子进程的所有输出。input_filter
将通过用户的所有键盘输入。
这是我写的代码:
import sys
import pexpect
_stdios = []
def read(data):
_stdios.append(("output", data.decode("utf8")))
return data
def write(data):
_stdios.append(("input", data.decode("utf8")))
return data
def capture_io(argv):
_stdios.clear()
child = pexpect.spawn(argv)
child.interact(input_filter=write, output_filter=read)
child.wait()
return _stdios
if __name__ == '__main__':
stdios_of_child = capture_io(sys.argv[1:])
print(stdios_of_child)
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[]) {
float radius, area;
printf("Enter radius of circle: ");
scanf("%f", &radius);
if (radius < 0) {
fprintf(stderr, "Negative radius values are not allowed.\n");
exit(1);
}
area = 3.14159 * radius * radius;
printf("Area: %f\n", area);
return 0;
}
哪个会产生以下输出:
$ python3 capture_io.py ./circle Enter radius of circle: 10 Area: 314.158997 [('output', 'Enter radius of circle: '), ('input', '1'), ('output', '1'), ('input', '0'), ('output', '0'), ('input', '\r'), ('output', '\r\n'), ('output', 'Area: 314.158997\r\n')]
从输出中可以看到,输入是逐字符处理的,并且也作为输出回显,从而造成混乱。是否可以更改此行为,以使我的input_filter
仅在按下Enter
时运行?
或更笼统地说,实现我的目标的最佳方法是什么(有或没有pexpect
)?
答案 0 :(得分:1)
当我开始编写一个助手时,我意识到主要的问题是输入应该被记录在行缓冲中,因此在输入到达程序之前就进行了退格和其他编辑,但是输出应该按顺序进行缓冲记录没有用新行终止的提示。
要捕获输出以进行记录,则需要一个管道,但是该管道会自动打开行缓冲。众所周知,伪终端解决了这个问题(expect
模块是围绕伪终端构建的),但是终端既具有输入又具有输出,因此我们只想对输出进行缓冲。
幸运的是,这里有stdbuf
实用程序。在Linux上,它会更改动态链接的可执行文件的C库功能。不能普遍使用。
我已经修改了Python双向复制程序来记录其复制的数据。与stdbuf
结合使用可产生所需的输出。
import select
import os
STDIN = 0
STDOUT = 1
BUFSIZE = 4096
def main(cmd):
ipipe_r, ipipe_w = os.pipe()
opipe_r, opipe_w = os.pipe()
if os.fork():
# parent
os.close(ipipe_r)
os.close(opipe_w)
fdlist_r = [STDIN, opipe_r]
while True:
ready_r, _, _ = select.select(fdlist_r, [], [])
if STDIN in ready_r:
# STDIN -> program
data = os.read(STDIN, BUFSIZE)
if data:
yield('in', data) # optional: convert to str
os.write(ipipe_w, data)
else:
# send EOF
fdlist_r.remove(STDIN)
os.close(ipipe_w)
if opipe_r in ready_r:
# program -> STDOUT
data = os.read(opipe_r, BUFSIZE)
if not data:
# got EOF
break
yield('out', data)
os.write(STDOUT, data)
os.wait()
else:
# child
os.close(ipipe_w)
os.close(opipe_r)
os.dup2(ipipe_r, STDIN)
os.dup2(opipe_w, STDOUT)
os.execlp(*cmd)
# not reached
os._exit(127)
if __name__ == '__main__':
log = list(main(['stdbuf', 'stdbuf', '-o0', './circle']))
print(log)
它打印:
[('out', b'Enter radius of circle: '), ('in', b'12\n'), ('out', b'Area: 452.388947\n')]
答案 1 :(得分:0)
我认为您无法轻松做到这一点,但是,我认为这应该对您有用:
output_buffer=''
def read(data):
output_buffer+=data
if data == '\r':
_stdios.append(("output", output_buffer.decode("utf8")))
output_buffer = ''
return data
答案 2 :(得分:0)
是否可以更改此行为,以使我的
input_filter
仅在按下Enter
时运行?
是,您可以通过从pexpect.spawn
继承并覆盖interact
方法来做到这一点。我很快就会来。
正如VPfB在their answer中指出的那样,您不能使用管道,我认为值得一提的是pexpect
's documentation中也解决了此问题。
您说的是
...输入被逐个字符处理,并作为输出回显...
如果您查看interact
的源代码,您会看到以下行:
tty.setraw(self.STDIN_FILENO)
这会将您的终端设置为raw mode:
输入可以逐个字符输入,...,并且禁止对终端输入和输出字符进行所有特殊处理。
这就是为什么您的input_filter
函数在每次按键时都会运行,并且看到退格键或其他特殊字符的原因。如果您可以注释掉这一行,则在运行程序时会看到以下内容:
$ python3 test.py ./circle Enter radius of circle: 10 10 Area: 314.158997 [('output', 'Enter radius of circle: '), ('input', '10\n'), ('output', '10\r\n'), ('output', 'Area: 314.158997\r\n')]
这也可以让您编辑输入(即12[Backspace]0
会给您相同的结果)。但是正如您所看到的,它仍然会回显输入。可以通过为儿童终端设置简单标志来禁用此功能:
mode = tty.tcgetattr(self.child_fd)
mode[3] &= ~termios.ECHO
tty.tcsetattr(self.child_fd, termios.TCSANOW, mode)
运行最新更改:
$ python3 test.py ./circle Enter radius of circle: 10 Area: 314.158997 [('output', 'Enter radius of circle: '), ('input', '10\n'), ('output', 'Area: 314.158997\r\n')]
宾果!现在,您可以从pexpect.spawn
继承并使用这些更改覆盖interact
方法,或使用Python的内置pty
模块实现相同的操作:
pty
:
import os
import pty
import sys
import termios
import tty
_stdios = []
def _read(fd):
data = os.read(fd, 1024)
_stdios.append(("output", data.decode("utf8")))
return data
def _stdin_read(fd):
data = os.read(fd, 1024)
_stdios.append(("input", data.decode("utf8")))
return data
def _spawn(argv):
pid, master_fd = pty.fork()
if pid == pty.CHILD:
os.execlp(argv[0], *argv)
mode = tty.tcgetattr(master_fd)
mode[3] &= ~termios.ECHO
tty.tcsetattr(master_fd, termios.TCSANOW, mode)
try:
pty._copy(master_fd, _read, _stdin_read)
except OSError:
pass
os.close(master_fd)
return os.waitpid(pid, 0)[1]
def capture_io_and_return_code(argv):
_stdios.clear()
return_code = _spawn(argv)
return _stdios, return_code >> 8
if __name__ == '__main__':
stdios, ret = capture_io_and_return_code(sys.argv[1:])
print(stdios)
与pexpect
:
import sys
import termios
import tty
import pexpect
_stdios = []
def read(data):
_stdios.append(("output", data.decode("utf8")))
return data
def write(data):
_stdios.append(("input", data.decode("utf8")))
return data
class CustomSpawn(pexpect.spawn):
def interact(self, escape_character=chr(29),
input_filter=None, output_filter=None):
self.write_to_stdout(self.buffer)
self.stdout.flush()
self._buffer = self.buffer_type()
mode = tty.tcgetattr(self.child_fd)
mode[3] &= ~termios.ECHO
tty.tcsetattr(self.child_fd, termios.TCSANOW, mode)
if escape_character is not None and pexpect.PY3:
escape_character = escape_character.encode('latin-1')
self._spawn__interact_copy(escape_character, input_filter, output_filter)
def capture_io_and_return_code(argv):
_stdios.clear()
child = CustomSpawn(argv)
child.interact(input_filter=write, output_filter=read)
child.wait()
return _stdios, child.status >> 8
if __name__ == '__main__':
stdios, ret = capture_io_and_return_code(sys.argv[1:])
print(stdios)