我试图通过Python运行几行shell命令,这些shell命令如下:
sudo apt-get install xxx | sudo apt-get update
cd ~/somefolder
make && sudo make install
我希望逐行运行这些命令行,例如:
for line in commands:
Run(line) # line could be any valid shell commands
内部函数Run,我想捕获shell命令生动的输出,并进行处理。以下是我尝试过的方法:
from subprocess import Popen, PIPE, STDOUT
import shlex
def Run(line):
process = Popen(shlex.split(line), stdout=PIPE, stderr=STDOUT)
while True:
output = process.stdout.readline()
if process.poll() is not None:
break
if output:
# process output
print output.decode("utf-8")
此解决方案无法处理管道命令。我也尝试过:
process = Popen(["/bin/sh", "-c", line], stdout=PIPE, stderr=STDOUT)
这种方式无法正确重定向输出。
有人知道怎么做吗?谢谢!