Search code examples
pythonsubprocessstdoutpopenstderr

Using subprocess to call R from Python, want to keep STDOUT and ignore STDERR


So this code in Python that I have currently works in returning my STDOUT in the variable "run":

run = subprocess.check_output(['Rscript','runData.R',meth,expr,norm])

But it still prints to the screen all this ugly text from having to install a package in R, etc, etc. So I would like for that to be ignored and sent into STDERR. Is there any way to do this? This is what I'm currently working on but it doesn't seem to work. Again, I just want it to ignore what it is printing to the screen except the results. So I want to ignore STDERR and keep STDOUT. Thank you!

run = subprocess.Popen(['Rscript','runData.R',meth,expr,norm],shell=False,   stdout=subprocess.PIPE,stderr=devnull)

Solution

  • To avoid piping stderr entirely you may redirect it to os.devnull:

    os.devnull

    The file path of the null device. For example: '/dev/null' for POSIX, 'nul' for Windows. Also available via os.path.

    import os
    import subprocess
    with open(os.devnull) as devnull:
        subprocess.Popen([cmd arg], stdout=subprocess.PIPE, stderr=devnull)