python - Truncate stdout of subprocess.run() without shell=True
问题描述
I'm running a binary executable from Python using the subprocess.run()
command and the command spits out about 20MB of text data to stdout. I'm only interested in the first few lines of the output and loading the entire output of the command into the memory takes a very long time (about 10 seconds).
I would like to read stdout of the command up the 10th line and then truncate all other output. What I would like to achieve is the equivalend of running command | head
(which is super fast), but I have the shell=False
set which does not allow the use of pipes.
Is there any way I can truncate the output of stdout to just a few lines/bytes without loading it all into memory? I already tried the bufsize=
parameter, but it had no effect.
解决方案
When using subprocess.Popen
you can have access to the subprocess's stdout and read as many lines as you want
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
lines_to_read = 10
for i in range(lines_to_read):
print(p.stdout.readline())
推荐阅读
- terraform - 为什么 terraform 在以下琐碎场景中无法正确计算局部变量?
- php - magento1.9.1 有没有办法让它在 xampp 3.2.4 上与 php7.4.4 一起工作
- android - 带有图像的 Android Firebase 通知不起作用
- c# - 无法在 EF 访问的存储过程中将 NVARCHAR 转换为 datetime2
- excel - 如何以这种方式将数据粘贴到列和行中
- java - 为什么我在 Java 中使用级联 if 时会出现错误?
- javascript - JS CryptoJS 加密 -> PHP OpenSSL 解密:密码改变长度
- java - 如何从注释处理器创建文件名中带有空格的资源
- python - 匹配 Python Regex 中变量之前遇到的最后两个 html 'class' 属性
- python - 通过 tensorflow GFile 保存 numpy zip 文件失败