6

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]
Harpal
  • 12,057
  • 18
  • 61
  • 74
  • The answers which recommend `Popen` were basically correct in 2012 when this question was asked, but the modern correct answer is to use `subprocess.run`, or `subprocess.check_output` if you need a simple API and/or compatibility back to older Python versions. [The `subprocess` documentation](https://docs.python.org/3/library/subprocess.html) spells this out, in the very first paragraph of the first section; *"The recommended approach to invoking subprocesses is to use the `run()` function for all use cases it can handle.*" – tripleee Mar 04 '22 at 12:32

3 Answers3

5

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

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

Rob Wouters
  • 15,797
  • 3
  • 42
  • 36
  • This was correct in 2012, but the recommended solution now is to avoid `Popen` unless your use case requires it. – tripleee Mar 04 '22 at 12:34
4

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
hughdbrown
  • 47,733
  • 20
  • 85
  • 108
1

You should use subprocess

    try:            
        subprocess.check_output(['./test.out', 'new_file.mfj', 'delete1.out'], shell=True, stderr=subprocess.STDOUT)
    except subprocess.CalledProcessError as exception:
        print exception.output
alemol
  • 8,058
  • 2
  • 24
  • 29