06 December 2008

Python subprocess Module example: using Popen()


#!/usr/bin/python

from subprocess import *

cmd1 = "tail"
cmd1Arg1 = "-n 3"
cmd1Arg2 = "/var/log/syslog"

p1 = Popen([cmd1, cmd1Arg1, cmd1Arg2], stdout=PIPE)
print p1.communicate()[0]

p1 = Popen(["tail", "-n 3", "/var/log/syslog"], stdout=PIPE)
print p1.communicate()[0]




And the output of this thing:



joe@adam:~/Documents$ python popen-example.py

Dec 6 14:38:27 adam hddtemp[6067]: /dev/sda: TOSHIBA MK8034GSX: 38 C
Dec 6 14:43:27 adam hddtemp[6067]: /dev/sda: TOSHIBA MK8034GSX: 38 C
Dec 6 14:48:27 adam hddtemp[6067]: /dev/sda: TOSHIBA MK8034GSX: 38 C

Dec 6 14:38:27 adam hddtemp[6067]: /dev/sda: TOSHIBA MK8034GSX: 38 C
Dec 6 14:43:27 adam hddtemp[6067]: /dev/sda: TOSHIBA MK8034GSX: 38 C
Dec 6 14:48:27 adam hddtemp[6067]: /dev/sda: TOSHIBA MK8034GSX: 38 C

joe@adam:~/Documents$