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

问题描述 投票:1回答:1

我正在尝试将顶级-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'的多个值

python subprocess
1个回答
1
投票

试试这个。

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

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

© www.soinside.com 2019 - 2024. All rights reserved.