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]
This entry was written by Sunng , posted on Thursday November 12 2009at 05:11 pm , filed under 把戏 and tagged , . Bookmark the permalink . Post a comment below or leave a trackback: Trackback URL.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word