将find命令的输出转换为python中的字符串数组

时间:2014-12-13 15:21:18

标签: python string python-2.7 subprocess

我想模拟以下unix命令:

f=`find . -name "*.pdf"`
for file in $f; do echo "$f"; done

我有以下python命令:

out= subprocess.check_output(["/usr/bin/find", ".", "-name",  "*.pdf"]).strip()

但我无法访问out[0]out[1]等等。是否可以将python中的输出作为字符串数组返回,因此我可以迭代它们中的每一个并用它做一些事情?感谢

1 个答案:

答案 0 :(得分:2)

str.strip()删除字符串周围的空格。您需要str.splitlines来分割行:

>>> 'a\nb'.strip()
'a\nb'
>>> 'a\nb\n'.splitlines()
['a', 'b']

out = subprocess.check_output(["/usr/bin/find", ".", "-name",  "*.pdf"]).splitlines()