私はこの種の目的のためにpythonでこのユーティリティ関数を書いた
(一時ファイルを使用する理由は、サブプロセスを開いてsubprocess.PIPEを使用してstdoutを取得した場合、stdoutが64kを超えるデータになると、Pythonはちょうどハングします)。
import logging
import tempfile
import subprocess
import os
def getPipedCommandOut(cmd):
"""
cmd - command to execute
gathers output of command (stderr and stdout) into a temp file
returns the output of the command
"""
logging.debug('starting %s' % cmd)
temp = tempfile.TemporaryFile('w+t')
try:
p = subprocess.Popen(cmd, stderr=subprocess.STDOUT,stdout=temp.fileno(), shell=True)
#pid, status = os.waitpid(p.pid,0) #@UnusedVariable
status = p.wait()
temp.seek(0)
out = temp.read()
if status != 0:
raise CommandRunError("COMMAND: %s\tFAILED: %s%s%s" % (cmd, status, os.linesep, out))
logging.debug('finished %s' % cmd)
finally:
temp.close()
return out
あなたのコードで使用する:
lspciOutput = getPipedCommandOut('lspci | grep VGA')
for line in lspciOutput:
count = count + 1