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()
                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)
                        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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With