Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Catching the output from subprocess.call with stdout

Tags:

python

So im trying to save the output from my subprocess.call but I keep getting the following error: AttributeError: 'int' object has no attribute 'communicate'

Code is as follows:

p2 = subprocess.call(['./test.out', 'new_file.mfj', 'delete1.out'], stdout = PIPE)
output = p2.communicate[0]
like image 428
Harpal Avatar asked Jan 03 '12 14:01

Harpal


People also ask

How do I get stdout from subprocess run Python?

To capture the output of the subprocess. run method, use an additional argument named “capture_output=True”. You can individually access stdout and stderr values by using “output. stdout” and “output.

How do you check subprocess output?

The subprocess. check_output() is used to get the output of the calling program in python. It has 5 arguments; args, stdin, stderr, shell, universal_newlines. The args argument holds the commands that are to be passed as a string.

How does subprocess run get return value?

subprocess. check_output() is the one that runs the command and returns the return value. If you want the output write your value to STDOUT and use check_output() to get the value.

What does stdout subprocess PIPE mean?

stdout=PIPE means that subprocess' stdout is redirected to a pipe that you should read e.g., using process.communicate() to read all at once or using process.stdout object to read via a file/iterator interfaces.


2 Answers

You're looking for subprocess.Popen() instead of call().

You also need to change it to p2.communicate()[0].

like image 87
Rob Wouters Avatar answered Oct 19 '22 23:10

Rob Wouters


That's because subprocess.call returns an int:

subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)

    Run the command described by args. Wait for command to complete, then return the returncode attribute.

It looks like you want subprocess.Popen().

Here's a typical piece of code I have to do this:

p = Popen(cmd, stdout=PIPE, stderr=PIPE, bufsize=256*1024*1024)
output, errors = p.communicate()
if p.returncode:
    raise Exception(errors)
else:
    # Print stdout from cmd call
    print output
like image 24
hughdbrown Avatar answered Oct 20 '22 00:10

hughdbrown