50

I need to store the result of a shell command that I executed in a variable, but I couldn't get it working. I tried like:

import os    

call = os.system("cat syscall_list.txt | grep f89e7000 | awk '{print $2}'")
print call

But it prints the result in terminal and prints the value of call as zero, possibly indicating as success. How to get the result stored in a variable?

UdonN00dle
  • 723
  • 6
  • 28
user567879
  • 5,139
  • 20
  • 71
  • 105
  • 1
    see here: http://stackoverflow.com/questions/1410976/equivalent-of-backticks-in-python – georg Dec 28 '11 at 17:46

4 Answers4

59

Use the subprocess module instead:

import subprocess
output = subprocess.check_output("cat syscall_list.txt | grep f89e7000 | awk '{print $2}'", shell=True)

Edit: this is new in Python 2.7. In earlier versions this should work (with the command rewritten as shown below):

import subprocess
output = subprocess.Popen(['awk', '/f89e7000/ {print $2}', 'syscall_list.txt'], stdout=subprocess.PIPE).communicate()[0]

As a side note, you can rewrite

cat syscall_list.txt | grep f89e7000

To

grep f89e7000 syscall_list.txt

And you can even replace the entire statement with a single awk script:

awk '/f89e7000/ {print $2}' syscall_list.txt

Leading to:

import subprocess
output = subprocess.check_output(['awk', '/f89e7000/ {print $2}', 'syscall_list.txt'])
Rob Wouters
  • 15,797
  • 3
  • 42
  • 36
  • I am using python 2.6.6 and it gives me error: `AttributeError: 'module' object has no attribute 'check_output' ` – user567879 Dec 28 '11 at 17:50
  • @user567879, You are right. This function was added in Python 2.7. I'll edit in a method for Python 2.6. – Rob Wouters Dec 28 '11 at 17:55
  • What if i need to pass a python variable as an argument to the executed shell command? – user567879 Dec 29 '11 at 02:32
  • @user567879: Just do it how you would normally put a variable in a list, i.e. `['awk', '/f89e7000/ {print $2}', filename]`, and pass that to Popen(). – Rob Wouters Dec 31 '11 at 18:12
17

In python 3 you can use

import subprocess as sp
output = sp.getoutput('whoami --version')
print (output)

``
Prakash D
  • 403
  • 4
  • 6
13

os.popen works for this. popen - opens a pipe to or from command. The return value is an open file object connected to the pipe, which can be read. split('\n') converts the output to list

import os
list_of_ls = os.popen("ls").read().split('\n')
print list_of_ls
import os
list_of_call = os.popen("cat syscall_list.txt | grep f89e7000 | awk '{print $2}'").read().split('\n')
print list_of_call
11

commands.getstatusoutput would work well for this situation. (Deprecated since Python 2.6)

import commands
print(commands.getstatusoutput("cat syscall_list.txt | grep f89e7000 | awk '{print $2}'"))
UdonN00dle
  • 723
  • 6
  • 28
enderskill
  • 7,354
  • 3
  • 24
  • 23