1
votes

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'

1
You need to pass subprocess.Popen(["top", "n1"], stdout .. ) instead of just ("top", "n1" ... - Rocky Li
It's giving me a top error now so that's better. top -n1 is a valid top command but it is throwing a top error. I'm guessing I need to push an array of arguments, but how does top -n1 work from CLI but in this case it throws a top error. If I push the "-n1" into the array it hangs. - Ehren
I just did, it hangs which is weird. I wonder if there is a problem with p.communicate - Ehren

1 Answers

1
votes

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.