在python中创建代理buffed stdout / stdin

时间:2018-08-25 18:11:37

标签: python subprocess

当前,vim有一个错误,即发送大字符串会导致死锁。 https://github.com/vim/vim/issues/2548讨论仍在进行中。

作为一种解决方法,我想到了使用python作为代理可执行文件,该文件将自动缓冲stdout / stdin / stderr,因此不会挂起。

如果我想在vim中启动executable,我首先要启动一个看起来像python proxy.py -- executable -arg0 -arg1的python脚本。然后,Python将使用适当的参数启动可执行文件,并缓冲stdout和stdin,因此vim一次只能获取1024个字节,而python一次只能读取1024个字节。

在python中不阻塞的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

此示例对我有用:

import subprocess
import sys

BUFSIZE = 1024    

p = subprocess.Popen(sys.argv[1:], stdin=subprocess.PIPE, bufsize=BUFSIZE)

while True:
    chunk = sys.stdin.read(BUFSIZE)
    if not chunk:
        break
    p.stdin.write(chunk)
    p.stdin.flush()

p.stdin.close()
p.wait()

我用

进行了测试
ls -lR | python proxy.py cat -n

echo 123 | python proxy.py cat -n