无法在python中执行终端命令(顶部) [英] Not able to execute terminal command(top) in python

查看:178
本文介绍了无法在python中执行终端命令(顶部)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下命令:

top -d 1.0 -n 1| grep Mem

当我在终端中执行它时,我得到:

KiB Mem : 16330216 total,  3902792 free, 10619512 used,  1807912 buff/cache
KiB Swap:  8509436 total,  4584448 free,  3924988 used.  4848204 avail Mem 

我想将此输出保存在文本文件中. 我想每10秒跟踪一次.

因此,我尝试:

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

但是我只能得到 3 的印刷.

我希望将完整的信息存储在文本文件中.

解决方案

输出( 3 )的原因是os.system()不返回写入stdout的内容,而是返回执行命令的值(通常不会打印出来,因此用户看不到).

您当然想获得stdout输出.最简单的方法是使用subprocess.run()而不是os.system().通常建议使用subprocess模块,而不是os.system(),因为它具有更大的功能.

此外,除了执行grep之外,还可以在Python本身中过滤输出数据.这更简单,不需要管道shell命令.管道shell命令需要shell=True作为subprocess.run()的参数,这可能很危险,尤其是在运行sudo时,因为它可能会导致执行程序的人访问整个系统,因此请谨慎处理.我认为您当前的程序没有风险,但是事情会发生变化和演变,突然之间……... p>

因此,解决您的问题的方法将是

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)

不幸的是,我目前不在Linux机器上,因此我无法测试代码,这意味着可能存在一些小问题,但是请尝试一下,让我知道它是否可以满足您的要求.

还请注意,subprocess.run()需要一个相当新的Python版本(3.5或更高版本),否则您将不得不依赖p = subprocess.check_output(...)p.communicate().

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

这篇关于无法在python中执行终端命令(顶部)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆