相关疑难解决方法(0)

你怎么读斯坦丁?

我正在尝试做一些代码高尔夫挑战,但它们都需要输入stdin.我如何在Python中获得它?

python stdin

1389
推荐指数
18
解决办法
150万
查看次数

逐行读取子进程标准输出

我的python脚本使用subprocess来调用非常嘈杂的linux实用程序.我想将所有输出存储到日志文件中并向用户显示一些输出.我认为以下内容可行,但在实用程序产生大量输出之前,输出不会显示在我的应用程序中.

#fake_utility.py, just generates lots of output over time
import time
i = 0
while True:
   print hex(i)*512
   i += 1
   time.sleep(0.5)

#filters output
import subprocess
proc = subprocess.Popen(['python','fake_utility.py'],stdout=subprocess.PIPE)
for line in proc.stdout:
   #the real code does filtering here
   print "test:", line.rstrip()
Run Code Online (Sandbox Code Playgroud)

我真正想要的行为是过滤器脚本在从子进程接收时打印每一行.Sorta就像tee使用python代码一样.

我错过了什么?这甚至可能吗?


更新:

如果将a sys.stdout.flush()添加到fake_utility.py,则代码在python 3.1中具有所需的行为.我正在使用python 2.6.您会认为使用proc.stdout.xreadlines()将与py3k一样工作,但事实并非如此.


更新2:

这是最小的工作代码.

#fake_utility.py, just generates lots of output over time
import sys, time
for i in range(10):
   print i
   sys.stdout.flush()
   time.sleep(0.5)

#display out put line by …
Run Code Online (Sandbox Code Playgroud)

python subprocess

216
推荐指数
8
解决办法
32万
查看次数

标签 统计

python ×2

stdin ×1

subprocess ×1