Anubhav Dinkar
Anubhav Dinkar

Reputation: 413

Is there a way I can store the output of a terminal command into a file using python?

I want to store the output of the terminal command top into a file, using Python. In the terminal, when I type top and hit enter, I get an output that is real time, so it keeps updating. I want to store this into a file for a fixed duration and then stop writing.

file=open("data.txt","w")
file.flush()
import os,time
os.system("top>>data.txt -n 1")
time.sleep(5)
exit()
file.close()

I have tried to use time.sleep() and then exit(), but it doesn't work, and the only way top can be stopped is in the terminal, by Control + C The process keeps running and the data is continuously written onto the file, which is not ideal, as one would guess

For clarity: I know how to write the output on to the file, I just want to stop writing after a period

Upvotes: 0

Views: 158

Answers (2)

Henry
Henry

Reputation: 54

The issue you could be facing is that os.system starts the process as part of the current process. So the rest of your script will not be run until the command you run has completed execution.

I think what you want to be doing is executing your console command on another thread so that the thread running your python script can continue while the command runs in the background. See run a python program on a new thread for more info.

I'd suggest something like (this is untested):

import os
import time
import multiprocessing

myThread = multiprocessing.process(target=os.system,  args=("top>>data.txt -n 1",))
myThread.start()

time.sleep(5)
myThread.terminate()

That being said, you may need to consider the thread safety of os.system(), if it is not thread safe you'll need to find an alternative that is.

Something else worth noting (and that I know little about) is that it may not be ideal to terminate threads in this way, see some of the answers here: Is there any way to kill a Thread?

Upvotes: 0

Serge Ballesta
Serge Ballesta

Reputation: 149125

system will wait for the end of the child process. If you do not want that, the Pythonic way is to directly use the subprocess module:

import subprocess

timeout=60   # let top run for one minute
file=open("data.txt","w")
top = subprocess.Popen(["top", "-n", 1], stdout=file)
if top.wait(timeout) is None:      # wait at most timeout seconds
    top.terminate()                # and terminate child

The panonoic way (which is highly recommended for robust code) would be to use the full path of top. I have not here, because it may depend on the actual system...

Upvotes: 2

Related Questions