问题
I have this command:
top -d 1.0 -n 1| grep Mem
when i execute it in terminal i get:
KiB Mem : 16330216 total, 3902792 free, 10619512 used, 1807912 buff/cache
KiB Swap: 8509436 total, 4584448 free, 3924988 used. 4848204 avail Mem
I want to save this output in a text file. I want to keep a track of this every 10 seconds.
Therefore i tried:
def repeat():
print(time.ctime())
threading.Timer(10, repeat).start()
f= open('ss.txt', 'w')
top= os.system("sudo top -d 1.0 -n 1| grep Mem")
s=str(top)
text = f.write(s)
print(text)
repeat()
But i am only gettin 3 printed.
I want the complete information to be stored in text file.
回答1:
The reason for your output (3) is that os.system()
does not return what is written to stdout
but the the return value of the executed command (which is normally not printed and therefore not seen by the user).
You, of course, want to get the stdout
output. The simplest way to get that, is to use subprocess.run()
rather than os.system()
. It is generally adviced to use the subprocess
module, over os.system()
due to its greater capabilities.
Also, instead of doing a grep
it is possible to filter the output data in Python itself. This is simpler and removes the need for piping shell commands. Piping shell commands requires shell=True
as parameter to subprocess.run()
which may be dangerous, especially if running sudo
, as it may allow the one executing the program access to all of the system, is not handled carefully. I don't think it is a risk with your current program, but things change and evolve, and all of a sudden it is...
Thus, a solution to your problem would be
import subprocess
cmd = ['sudo', 'top', '-d', '1.0', '-n', '1']
p = subprocess.run(cmd, stdout=subprocess.PIPE, universal_newlines=True)
with open('ss.txt', 'w') as f:
for line in p.stdout.split('\n'):
if 'Mem' in line:
f.write(line)
Unfortunately I am currently not a on Linux machine, so I cannot test the code, which means there may be minor issues, but try it and let me know if it does what you want.
Also note that subprocess.run()
requires a rather new version of Python (3.5 or newer) otherwise you have to fall back on p = subprocess.check_output(...)
and p.communicate()
.
回答2:
try this
def repeat():
print(time.ctime())
threading.Timer(10, repeat).start()
top= os.system("sudo top -d 1.0 -n 1| grep Mem > a.txt")
with open('a.txt', 'r') as f:
print(str(f.read()))
repeat()
来源:https://stackoverflow.com/questions/49766878/not-able-to-execute-terminal-commandtop-in-python