Taking bash command results and using it in python

I am trying to write code in python that will take some information from above and put it in a file. I want to just write the name of the application and generate the file. The problem I am facing is that I cannot get the output of the pidof command, so I can use it in python. My code is as follows:

import os a = input('Name of the application') val=os.system('pidof ' + str(a)) os.system('top -d 30 | grep' + str(val) + '> test.txt') os.system('awk '{print $10, $11}' test.txt > test2.txt') 

The problem is that val always has 0, but the command returns the pid I want. Any input would be great.

+4
source share
2 answers

First, using input() not recommended, as it expects the user to type the correct Python expressions. Use raw_input() :

 app = raw_input('Name of the application: ') 

Further, the return value from system('pidof') not a PID code, it is the exit code from the pidof command, i.e. zero on success, and not zero on error. You want to capture pidof output .

 import subprocess # Python 2.7 only pid = int(subprocess.check_output(['pidof', app])) # Python 2.4+ pid = int(subprocess.Popen(['pidof', app], stdout=subprocess.PIPE).communicate()[0]) # Older (deprecated) pid = int(os.popen('pidof ' + app).read()) 

The next line does not contain a space after grep and would lead to a command like grep1234 . Using the % line format operator will make this a little easier:

 os.system('top -d 30 | grep %d > test.txt' % (pid)) 

The third line is badly quoted and should lead to a syntax error. Watch out for single quotes inside single quotes.

 os.system("awk '{print $10, $11}' test.txt > test2.txt") 
+8
source

Instead of os.system, I recommend you use a subprocess module: http://docs.python.org/library/subprocess.html#module-subprocess

With this module you can communicate (input and output) using the shell. The documentation explains how to use it.

Hope this helps!

+2
source

All Articles