Saving top output using python

I have been playing with Python for almost five days, and I honestly enjoy it. I have this problem and I could not solve it.
The task is to repeat the output of the top command every 10 seconds and save it to 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() 
+4
source share
4 answers

The main problem here is that the top call is not interrupted immediately, but runs continuously in loops to display new data. You can change this behavior 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) 
+3
source

It is advisable to use subprocess to call another process. You need to pass the file object file to which you want to write the output. eg

  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 the command to a file, which you can read later.

+1
source

You can also use the time.sleep() function and wait 10 seconds before continuing.
Not sure if this is what you want ...

 import time,os def repeat(seconds,filename): while True: print(time.ctime()) f = open(filename, 'w') top = os.system("sudo top -p 2948") s = str(top) time.sleep(seconds) f.write(s) repeat(5,'ss.txt') 

Also

  • f.write returns None , since it writes to a file, and does not return any value, so it is useless to store this value.
  • check PEP 324 , it notes the features of the subprocess module. (thanks to @ajm)
  • subprocess.Popen() has many functions (tools), so it can replace many other "tools" (see here ) so you can also think about it.
+1
source

Firstly, your code is not formed correctly, it should look something like this:

 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() 

Then you may need to study the subprocess module - its more modern and kosher way to call external commands than os.system. However, if your code works, what is the actual problem?

0
source

All Articles