简体   繁体   中英

How to write top output to a file in python?

I'm trying to write top -n1 to a file in python. It is giving a buffer size error. I'm new to python, and don't understand this as it looks pretty straight forward.

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

Error:

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

File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 659, in init raise TypeError("bufsize must be an integer") TypeError: bufsize must be an integer

Adding in buffsize as 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()

Error:

p = subprocess.Popen("top", "n1",stdout=subprocess.PIPE, shell=False, bufsize =1) TypeError: init () got multiple values for keyword argument 'bufsize'

Try this.

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

The "b" which stands for batch mode solves the top: failed tty get error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM