Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Suppressing output in python subprocess call [duplicate]

For the following command:

subprocess.call(shlex.split(
            """/usr/local/itms/bin/iTMSTransporter -m lookupMetadata 
              -apple_id %s -destination %s"""%(self.apple_id, self.destination))

It prints the entire output into the Terminal window. How would I suppress ALL output here? I tried doing subprocess.call(shlex.split(<command> > /dev/null 2&1)), but it didn't produce the required results. How would I do this here?

like image 389
David542 Avatar asked Apr 20 '12 18:04

David542


2 Answers

You can use the stdout= and stderr= parameters to subprocess.call() to direct stdout or stderr to a file descriptor of your choice. So maybe something like this:

import os

devnull = open(os.devnull, 'w')
subprocess.call(shlex.split(
    '/usr/local/itms/bin/iTMSTransporter -m lookupMetadata '
    '-apple_id %s -destination %s' % (self,apple_id, self.destination)),
  stdout=devnull, stderr=devnull)

Using subprocess.PIPE, if you're not reading from the pipe, could cause your program to block if it generates a lot of output.

Update

As @yanlend mentions in a comment, newer (3.x) versions of Python include subprocess.DEVNULL to solve this problem in a more convenient and portable fashion. In that case, the code would look like:

subprocess.call(shlex.split(
    '/usr/local/itms/bin/iTMSTransporter -m lookupMetadata '
    '-apple_id %s -destination %s' % (self,apple_id, self.destination)),
  stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
like image 175
larsks Avatar answered Oct 24 '22 07:10

larsks


What worked for me is appending 2>/dev/null at the end of the command.

like image 21
David542 Avatar answered Oct 24 '22 05:10

David542