Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store the result of an executed shell command in a variable in python? [duplicate]

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?

like image 222
user567879 Avatar asked Dec 28 '11 17:12

user567879


People also ask

How do you store a command in a variable?

To store the output of a command in a variable, you can use the shell command substitution feature in the forms below: variable_name=$(command) variable_name=$(command [option ...] arg1 arg2 ...) OR variable_name='command' variable_name='command [option ...]


1 Answers

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']) 
like image 112
Rob Wouters Avatar answered Sep 21 '22 00:09

Rob Wouters