首页 > 解决方案 > 如何将顶部输出写入python中的文件?

问题描述

我正在尝试将 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 raise TypeError("bufsize must be an integer") TypeError: bufsize must be an整数

将 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 () got multiple values for keyword argument 'bufsize'

标签: pythonsubprocess

解决方案


尝试这个。

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

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


推荐阅读