1

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'

4
  • You need to pass subprocess.Popen(["top", "n1"], stdout .. ) instead of just ("top", "n1" ... Commented Apr 5, 2019 at 14:35
  • 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. Commented Apr 5, 2019 at 14:40
  • I just did, it hangs which is weird. I wonder if there is a problem with p.communicate Commented Apr 5, 2019 at 14:43
  • stackoverflow.com/questions/17824096/… Commented Apr 5, 2019 at 14:44

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.