One nice feature of Perl is how easy it is to execute external programs. Therefore, one can use the built-in qx() function ("quote execute"). For example:
my $output = qx(cat /var/log/messages | grep fail);
After the above line has been executed, the variable output holds all system messages that contain the substring "fail". To achieve an equivalent solution with Python prior to version 2.6, the popen() function of the os module could be used:
import os
f = os.popen('cat /var/log/messages | grep fail', 'r')
output = f.readlines()
f.close()
Or shorter:
output = os.popen('cat /var/log/messages | grep fail').readlines()
Since the above is marked as deprecated starting with Python 2.6, a less intuitionally solution has to be implemented by using the subprocess module.
import subprocess
cmd = 'cat /var/log/messages | grep fail'
f = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout
output = f.readlines()
f.close()
Or shorter:
output = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.readlines()
Putting it all together, here's the qx() function written as a one-liner:
def qx(cmd):
return subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout.readlines()
IMPORTANT: Make sure that you don't execute any given string, but only those who you trust!
References:
http://docs.python.org/2/library/subprocess.html#subprocess-replacements