Sai Sanapureddy
Sai Sanapureddy

Reputation: 23

python script to capture output of top command

I was trying to capture output of top command using the following python script:

    import os
    process = os.popen('top')
    preprocessed = process.read()
    process.close()
    output = 'show_top.txt'
    fout = open(output,'w')
    fout.write(preprocessed)
    fout.close()

However, the script does not work for top. It gets stuck for a long time. However it works well with commands like 'ls'. I have no clue why this is happening?

Upvotes: 2

Views: 6099

Answers (2)

oetzi
oetzi

Reputation: 1052

-b argument required when stdout read from python

os.popen('top -b -n 1')

top -b -n 1

Upvotes: 1

shx2
shx2

Reputation: 64318

Since you're waiting for the process to finish, you need to tell top to only print its output once, and then quit.

You can do that by running:

top -n 1

Upvotes: 1

Related Questions