Skip to content Skip to sidebar Skip to footer

Not Able To Execute Terminal Command(top) In Python

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

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

withopen('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().

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

Post a Comment for "Not Able To Execute Terminal Command(top) In Python"