views:

421

answers:

1

i am using subprocess to call a external program plink.exe to login to a server, but when i call communicate to read the output, it blocking. the code is below:

 import subprocess
 process = subprocess.Popen('plink.exe [email protected] -pw 123456'.split(), shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
 print process.communicate() #block here

i know the block is because the plink.exe it still running. but i need to read the output before the subprocess terminal. is there anyway to do it? thanks in advance.

+4  A: 

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.

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.

Thomas Wouters