预计发送线太慢

pexpect sendline is too slow

我正在 运行使用 pexpect 创建一个子进程。我通过 sendline 和 readline 断断续续地与它通信。 cProfile 表明我的程序大部分时间都在等待 sendline 完成,这不是我们想要的行为。 Python伪代码:

def reset(self):
  self.proc = pexpect.spawn("node ./my_lovely_program.js")
...
def step(self, info):
    self.proc.sendline(info)
    while (my_condition):
        response = self.proc.readline().decode()
        # evaluate my_condition
    return retval

与此同时,在 Waiting for user to enter input in Node.js 的风格中,埋藏在我的节点应用程序中的是:

let ans = await this.askQuestion("");
// do_stuff(ans);

这会同时通过相关 class 的两个不同实例获得 运行。这一切都很好,运行s 令人满意。那我运行

python3 -m cProfile -s cumtime main.py

得到这个:

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
    498/1    0.002    0.000  262.820  262.820 {built-in method builtins.exec}
        1    0.107    0.107  262.820  262.820 main loop
        1    0.099    0.099  262.081  262.081 also main loop
     3774    0.022    0.000  214.272    0.057 main.py:24(step)
    33596  203.977    0.006  203.977    0.006 {built-in method time.sleep}
     3774    0.017    0.000  189.138    0.050 pty_spawn.py:570(sendline)
     3774    0.049    0.000  189.105    0.050 pty_spawn.py:526(send)
     3875    0.158    0.000   53.767    0.014 main.py:28(scrape_input)
    14756    0.052    0.000   53.434    0.004 spawnbase.py:459(readline)
    14756    0.056    0.000   53.382    0.004 spawnbase.py:240(expect)
    14756    0.072    0.000   52.985    0.004 spawnbase.py:343(expect_list)
    14756    0.242    0.000   52.848    0.004 expect.py:91(expect_loop)
    29721    0.235    0.000   47.113    0.002 pty_spawn.py:415(read_nonblocking)
    69657    0.113    0.000   46.250    0.001 pty_spawn.py:448(select)
    69657    0.103    0.000   46.137    0.001 utils.py:130(select_ignore_interrupts)
    69657   46.016    0.001   46.016    0.001 {built-in method select.select}
...

在它们之间,readline 尤其是 sendline 占据了 90% 以上的程序 运行time。大部分时间都花在睡觉上。这很可悲,我想修复它。我每次发送 20-30 个字符。我试过以其他方式从 stdin 读取(例如 https://www.dev2qa.com/node-js-get-user-input-from-command-line-prompt-example/) and am ready to keep going down that route if that's the way to go. (The issue I am having there is a separate one; on the second communication, the input gets read twice). Posix_spawn performance when capturing process output 使用 popen;我记得几个月前使用过它并且它死锁了。

pexpect 的 send() 默认等待时间为 50 毫秒。您可以通过设置禁用此功能:

proc.delaybeforesend = None

请参阅 the documentation 以了解他们为何延迟的解释。