如何在python中将顶级输出写入文件?

时间:2019-04-05 14:32:41

标签: python subprocess

我正在尝试将top -n1写入python中的文件。它给出了缓冲区大小错误。我是python的新手,对它不了解,因为它看起来很简单。

import subprocess
p = subprocess.Popen("top", "n1",stdout=subprocess.PIPE, shell=False)
(output, err) = p.communicate()
topfile = open("top.txt","w+")
topFile.write(output)
topFile.close()

错误:

  

p = subprocess.Popen(“ top”,“ n1”,stdout = subprocess.PIPE,shell = False)

     

文件   “ /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py”,   第659行, init       引发TypeError(“ bufsize必须为整数”)TypeError:bufsize必须为整数

将buffsize添加为int

import subprocess
p = subprocess.Popen("top", "n1",stdout=subprocess.PIPE, shell=False, bufsize =1)
(output, err) = p.communicate()
topHeavyFile = open("topHeavy.txt","w+")
topHeavyFile.write(output)
topHeavyFile.close()

错误:

  

p = subprocess.Popen(“ top”,“ n1”,stdout = subprocess.PIPE,shell = False,   bufsize = 1)TypeError: init ()获得了多个关键字值   参数'bufsize'

1 个答案:

答案 0 :(得分:1)

尝试一下。

import subprocess
p = subprocess.Popen(["top", "n1", "b"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, err = p.communicate()

代表批量模式的"b"解决了top: failed tty get错误。