python子进程存储列表中的每一行输出

时间:2013-04-03 11:53:44

标签: python subprocess line-by-line

我正在尝试将文件夹中的视频文件的尺寸存储到列表中。

#!/usr/bin/env python

# src_dimensions.py

# requires mediainfo package

import subprocess

proc = subprocess.Popen('mediainfo --Inform="Video;%Width%x%Height%\n" /home/saad/Videos/*.*', shell=True, stdout=subprocess.PIPE)

for line in iter(proc.stdout.readline,''):
   print line

此程序的结果输出为:

384x288640x480480x350352x162480x360640x360480x360384x288240x180320x240480x360384x288346x26

当我在终端中运行mediainfo命令时,每个视频维度都在换行符上:

384x288
640x480
480x350
352x162
480x360

我希望每个维度都作为单独的项目存储在列表中。我试图迭代stdout,但它不起作用。

更新#1

import subprocess
dim = []
proc = subprocess.Popen('mediainfo --Inform="Video;%Width%x%Height%\\n" /home/saad/Videos/*.*', shell=True, stdout=subprocess.PIPE)
for line in iter(proc.stdout.readline, ''):
   dim.append(line.rstrip('\n'))
print dim

由于@ Chakib的建议,这似乎给了我这个清单。

['440x360', '320x240', '480x360', '320x240', '480x360', '320x240', '320x240', '400x224', '']

1 个答案:

答案 0 :(得分:3)

\这是你想要的吗?

#!/usr/bin/env python
# src_dimensions.py
# requires mediainfo package
import subprocess, glob
globpattern = 'path/to/*.*'
cmd = ['mediainfo', '--Inform=Video;%Width%x%Height%\\n']
cmd.extend(glob.glob(globpattern))
proc = subprocess.Popen(cmd,stdout=subprocess.PIPE)
outputlines = filter(lambda x:len(x)>0,(line.strip() for line in proc.stdout))
print outputlines