【发布时间】:2018-01-21 17:00:00
【问题描述】:
我正在尝试创建一个执行环境/shell,它将在服务器上远程执行,它将 stdout、err、in 流式传输到套接字上以在浏览器中呈现。我目前已经尝试过使用subprocess.run 和PIPE 的方法。问题是该过程完成后我得到了标准输出。我想要实现的是逐行、伪终端的实现。
我目前的实现
test.py
def greeter():
for _ in range(10):
print('hello world')
greeter()
在外壳中
>>> import subprocess
>>> result = subprocess.run(['python3', 'test.py'], stdout=subprocess.PIPE)
>>> print(result.stdout.decode('utf-8'))
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world
如果我尝试使用pty 来尝试这个简单的实现,那该怎么做?
【问题讨论】:
-
尝试使用
bufsize=1参数子进程设置行缓冲区,并使用iter(result.stdout.readline, b'')读取包含在while True循环中的stdout
标签: python shell subprocess pty