Reputation: 264
I want to use data of the shell command top in a python program, i am trying to do this with subprocess module,
but, the top command runs in a way that it opens in the terminal with a kind of its screen, which requires the keyboard interrupt to get back to normal terminal.
So when i run command from python shell for getting output of top from linux shell, the scrip just goes in infinite loop, it never ends.
So suggest some ways to get a proper output of such commands like top.
Upvotes: 2
Views: 317
Reputation: 59426
In a general case, you will have to abort the subprocess after you got the output you want. You can typically do this by closing all connections to it, then upon its next output it will receive a SIGPIPE and typically terminate on its own.
In this particular case you can just call top
with option -n 1
to run just one iteration. This will make it terminate after displaying one screen:
import subprocess
output = subprocess.check_output([ 'top', '-n', '1' ])
print output
But beware! This output
will have a lot of terminal formatting sequences in it. So parsing it might be a bit difficult.
If you want more output, you should also consider option -b
(credit for this goes to @Klaus D.) which makes top not abort after reaching the current screen height.
Upvotes: 0
Reputation: 14369
man top
is very helpful.
You will find the -b
argument for batch mode and -n
for the number of iterations. Both together:
top -b -n 1
will give you the desired result.
Upvotes: 2