python子进程communication()块 [英] python subprocess communicate() block

查看:154
本文介绍了python子进程communication()块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 subprocess 模块来调用外部程序(plink.exe)以登录到服务器;但是当我打电话来交流以读取输出时,它阻塞了.代码如下:

I am using the subprocess module to call an external program (plink.exe) to log-in to a server; but when I call communicate to read the output, it is blocking. The code is below:

 import subprocess
 process = subprocess.Popen('plink.exe hello@10.120.139.170 -pw 123456'.split(), shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
 print process.communicate() #block here

我知道该块是因为plink.exe它仍在运行;但是我需要在子进程终止之前读取输出.反正有这样做吗?

I know the block is because plink.exe it still running; but I need to read the output before the subprocess terminates. Is there anyway to do that?

推荐答案

communicate方法的全部目的是等待过程完成并返回所有输出.如果您不想等待,请不要拨打communicate.而是从stdoutstderr属性读取以读取输出.

The whole purpose of the communicate method is to wait for the process to finish and return all the output. If you don't want to wait, don't call communicate. Instead, read from the stdout or stderr attribute to read the output.

如果该进程同时输出到stdoutstderr(并且您想分别读取),则必须小心地从两者中进行读取而不会阻塞,否则可能会死锁.在Windows上,这相当困难,您可能希望使用 pexpect 模块.

If the process outputs to both stdout and stderr (and you want to read it separately), you will have to be careful to actually read from both without blocking, or you can deadlock. This is fairly hard on Windows, and you may wish to use the pexpect module instead.

这篇关于python子进程communication()块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆