python无法在终端运行程序,无法在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 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.

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值