是否有一种“好的”方法来迭代shell命令的输出?
我正在寻找类似于以下内容的python:
ls | while read file; do
echo $file
done
请注意,'ls'只是shell命令的一个示例,它会将结果返回多行,因为'echo'只是:用它做一些事情。
我知道这些替代方案:Calling an external command in Python但我不知道使用哪一个或者是否有一个“更好”的解决方案。 (事实上,“更好”是这个问题的主要焦点。)
这是用python替换一些bash脚本。
答案 0 :(得分:9)
你可以打开一个烟斗(见doc):
import os
with os.popen('ls') as pipe:
for line in pipe:
print (line.strip())
在文档中,此语法已弃用,并替换为更复杂的subprocess.Popen
from subprocess import Popen, PIPE
pipe = Popen('ls', shell=True, stdout=PIPE)
for line in pipe.stdout:
print(line.strip())
答案 1 :(得分:0)
check_output会返回一个你可以解析的字符串。 call
将简单地重用现有的stdout / stderr / stdin,只返回进程退出代码。