我的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中,我想处理一条消息:
>>> message = sys.stdin.readlines()
Run Code Online (Sandbox Code Playgroud)
一切正常,但是......如何阻止它获取输入并将其保存到消息变量中?使用ctrl + c停止会停止整个过程,因此无需在任何地方保存输入.我想有一个简单的答案,我找不到...
我的问题如下:
我的pythons脚本通过sys.stdin接收数据,但它需要等到sys.stdin上有新数据可用.
如python的联机帮助页中所述,我使用以下代码,但它完全重载我的CPU.
#!/usr/bin/python -u
import sys
while 1:
for line in sys.stdin.readlines():
do something useful
Run Code Online (Sandbox Code Playgroud)
有没有什么好方法可以解决高CPU使用率?
编辑:
您的所有解决方案都不起作用.我告诉你我的问题.
您可以配置将每个日志发送到程序而不是写入日志文件的apache2守护程序.
这看起来像这样:
CustomLog "|/usr/bin/python -u /usr/local/bin/client.py" combined
Run Code Online (Sandbox Code Playgroud)
Apache2希望从我的脚本中始终运行,等待sys.stdin上的数据并解析它然后有数据.
如果我只使用for循环,脚本将退出,因为在某一点上,sys.stdin中没有数据,而apache2会说哦,你的脚本意外退出.
如果我使用while while循环,我的脚本将使用100%的cpu使用率.