子进程:从sigle行获取stdout

时间:2016-11-15 06:45:44

标签: python subprocess stdout

作为一个Python noob我需要在我的python脚本中运行第三方应用程序(将其标准输出写入单行,它们可能使用skip_eol=True之类的东西)并显示应用程序的标准输出住。

process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
for line in iter(process.stdout.readline, b''):
    print line.rstrip()

只允许我在子进程完成后获取stdout。 我不清楚我怎么能抓住整个标准杆?

1 个答案:

答案 0 :(得分:0)

尝试这样:

#!/usr/bin/env python2

import subprocess
import shlex

process = subprocess.Popen(shlex.split('./bash_1_line_per_second.sh'), stdout=subprocess.PIPE)

while process.poll() is None:
    print 'reading' # Just to understand better what is happening
    print process.stdout.read(1)

这时读取一个字符...是cmd binary的输出吗?在这种情况下,这可能不会起作用......

如果你提供cmd的输出我可以更精确!特别是,如果您需要帮助来重建单个字符的行。

这是我用来测试的bash脚本:

#!/bin/bash

counter=0
while [[ "a" == "a" ]]; do
  echo -n "This is the line number $counter"
  let counter+=1
  sleep 1
  if [[ $counter -eq 5 ]]; then 
      exit 0
  fi
done