简体   繁体   中英

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?

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

-b argument required when stdout read from python

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

top -b -n 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM