Use pipe in subprocess
问题: 您要通过python的subprocess模块执行一些命令,要在程序中获得命令的标准输出,此外,命令中还有管道操作。 解决: 以这个命令为例: cat /home/admin/deploy/log/2009-11-11.log |grep example.com |wc -l import subprocess cmd1 = ‘cat /home/admin/deploy/log/2009-11-11.log’ cmd2 = ‘grep example.com’ cmd3 = ‘wc -l’ pipe1 = subprocess.Popen(cmd1.split(), stdout=subprocess.PIPE) pipe2 = subprocess.Popen(cmd2.split(), stdin=pipe1, stdout=subprocess.PIPE) pipe3 = subprocess.Popen(cmd3.split(), stdin=pipe2, stdout=subprocess.PIPE) result = pipe3.communicate()[0]