17

我正在使用进程模块调用外部程序(plink.exe)来登录服务器;但是当我调用通信来读取输出时,它是阻塞的。代码如下:

 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它仍在运行;但我需要在子进程终止之前读取输出。有没有办法做到这一点?

4

3 回答 3

32

communicate方法的全部目的是等待进程完成并返回所有输出。如果您不想等待,请不要打电话communicate。相反,从stdoutorstderr属性中读取以读取输出。

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

于 2010-01-25T15:41:06.993 回答
0

我遇到了类似的情况,我必须执行一个命令lmstat -a,然后获取终端的输出。

如果您只需要运行单个命令然后读取输出,则可以使用以下代码:

import subprocess

Username = 'your_username'
Password = 'your_password'
IP = 'IP_of_system'
Connection_type = '-ssh' #can have values -ssh -telnet -rlogin -raw -serial

p = subprocess.Popen(['plink', Connection_type, '-l', Username, '-pw', Password, IP], \
                     shell = False, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
out, err = p.communicate('lmstat -a\nexit\n'.encode())
print(out.decode())
于 2012-12-11T11:48:32.663 回答
0

可能是因为“plink.exe”需要接受输入参数,如果你不传递它们,它将阻塞直到给出数据,你可以尝试在方法中添加参数communicate(input)

于 2018-10-22T03:20:05.090 回答