使用popen与python交互式shell交互



我正在尝试在python交互式shell中执行命令,并通过popen打印输出。

我从这个代码开始:

import subprocess
if __name__ == "__main__":
process = subprocess.Popen('python',
stdin=subprocess.PIPE,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE,
shell=True)
process.stdin.write('help()n'.encode())
process.stdin.flush()
output = process.stdout.read()
print(output)
process.stdin.write('qn'.encode())
process.stdin.flush()
output = process.stdout.read()
print(output)
process.stdin.write('exit()n'.encode())
process.stdin.flush()
output = process.stdout.read()
print(output)

然而,在线路process.stdout.read()处执行被阻止。

我在这里做错了什么?

Python 3文档中说

read(size=-1)
读取并返回最大大小的字节。如果参数被省略、无或为负数,数据被读取并返回,直到达到EOF。返回空字节对象如果流已经处于EOF。

您的read()是一个阻塞调用,请尝试使用某个大小进行读取,或者在读取之前尝试使用peek来确定缓冲区中是否有内容。

最新更新