Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

saving top output using python

Tags:

python

I have been playing with Python for almost five days and I honestly enjoy it.
I have this challenge and I couldn't solve it.
The challenge is to repeat the output of top command every 10 seconds and save it into a file.
Here is what I have done so far.

import time, os, threading

def repeat():
    print(time.ctime())
    threading.Timer(10, repeat).start()
    f = open('ss.txt', 'w')
    top = os.system("sudo top -p 2948")
    s = str(top)
    text = f.write(s)
    print(text)

repeat()
like image 801
user1763699 Avatar asked Jan 21 '13 10:01

user1763699


2 Answers

The main problem here is that a call to top does not terminate immediately but runs continuously in a loops to display new data. You can change this behaviour by specifying the -n1 option (-n allows you to specify the number of iterations).

Try something like this:

import subprocess

## use the following where appropriate within your loop
with open("ss.txt", "w") as outfile:
  subprocess.call("top -n1 -p 2948", shell=True, stdout=outfile)
like image 78
Shawn Chin Avatar answered Oct 11 '22 14:10

Shawn Chin


It is advisable to use subprocess for invoking another process. You need to pass the file object of the file where you want to write output. e.g.

    import time, os, threading, subprocess
    def repeat():
      print(time.ctime())
      threading.Timer(10, repeat).start()
      with open('ss.txt', 'w') as f:
          subprocess.call(["sudo","top","-p","2948"],stdout=f)

This should save the output of command to a file which you can read later.

like image 24
MoveFast Avatar answered Oct 11 '22 14:10

MoveFast