I am trying to write a code in python that will take some information from top and put it into a file.
I want to just write the name of the application and generate the file. The problem i am having is that i can’t get the output of the pidof command so i can use it in python. My code looks like this :
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 is returning the pid i want. Any input would be great.
First up, the use of
input()is discouraged as it expects the user to type in valid Python expressions. Useraw_input()instead:Next up, the return value from
system('pidof')isn’t the PID, it’s the exit code from thepidofcommand, i.e. zero on success, non-zero on failure. You want to capture the output ofpidof.The next line is missing a space after the
grepand would have resulted in a command likegrep1234. Using the string formatting operator%will make this a little easier to spot:The third line is badly quoted and should have caused a syntax error. Watch out for the single quotes inside of single quotes.