使用子进程从 Python 调用 R,希望保留 STDOUT 并忽略 STDERR

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

因此,我目前在 Python 中的这段代码用于在变量 "run" 中返回我的 STDOUT:

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

但它仍然会在屏幕上打印所有这些丑陋的文本,因为必须在 R 等中安装一个包,等等。所以我希望忽略它并将其发送到 STDERR。有什么办法吗?这就是我目前正在做的事情,但似乎没有用。同样,我只是希望它忽略它正在打印到屏幕上的内容,除了结果。所以我想忽略 STDERR 并保留 STDOUT。谢谢!

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

实际上我一发布就解决了我的问题!我很抱歉!它是这样工作的:

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

 final = output.stdout.read()

这忽略了命令行中的乱七八糟的东西,并将我的结果保存到最终版本中。

感谢大家的快速回复!

为了完全避免管道 stderr,您可以将其重定向到 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)