python subprocess communicate() block(python子进程通信()块)
问题描述
我正在使用子进程模块调用外部程序(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
.而是从 stdout
或 stderr
属性读取输出.
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.
如果进程同时输出到 stdout
和 stderr
(并且您想分别读取它),则必须小心地从两者中实际读取而不会阻塞,或者你可以死锁.这在 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子进程通信()块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:python子进程通信()块


基础教程推荐
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 筛选NumPy数组 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01