繁体   English   中英

通过subprocess.Popen在python中执行R脚本

[英]Executing an R script in python via subprocess.Popen

当我在R中执行脚本时,它是:

$ R --vanilla --args test_matrix.csv < hierarchical_clustering.R > out.txt

在Python中,如果我使用它,它可以工作:

process = subprocess.call("R --vanilla --args "+output_filename+"_DM_Instances_R.csv < /home/kevin/AV-labels/Results/R/hierarchical_clustering.R > "+output_filename+"_out.txt", shell=True)

但是这种方法不提供process.wait()函数。

所以,我想使用subprocess.Popen ,我试过:

process = subprocess.Popen(['R', '--vanilla', '--args', "\'"+output_filename+"_DM_Instances_R.csv\'",  '<', '/home/kevin/AV-labels/Results/R/hierarchical_clustering.R'])

但它没有用,Python只是打开R但没有执行我的脚本。

而不是'R',给它通往Rscript的路径。 我有同样的问题。 打开R但不执行我的脚本。 您需要调用Rscript(而不是R)来实际执行脚本。

retcode = subprocess.call("/Pathto/Rscript --vanilla /Pathto/test.R", shell=True)

这适合我。

干杯!

我已经把所有内容放入括号中解决了这个问题。

process = subprocess.Popen(["R --vanilla --args "+output_filename+"_DM_Instances_R.csv < /home/kevin/AV-labels/Results/R/hierarchical_clustering.R > "+output_filename+"_out.txt"], shell=True)
process.wait()

Keven的解决方案适合我的要求。 仅举几个关于@Kevin解决方案的例子。 您可以使用python样式的字符串将更多参数传递给rscript:

import subprocess

process = subprocess.Popen(["R --vanilla --args %s %d %.2f < /path/to/your/rscript/transformMatrixToSparseMatrix.R" % ("sparse", 11, 0.98) ], shell=True)
process.wait()

此外,为了使事情更容易,您可以创建一个R可执行文件。 为此,您只需在脚本的第一行添加:

#! /usr/bin/Rscript --vanilla --default-packages=utils

参考: 使用R作为Rscript此链接 的脚本语言

你永远不会完全执行它^^尝试以下

process = subprocess.Popen(['R', '--vanilla', '--args', '\\%s_DM_Instances_R.csv\\' % output_filename, '<', '/home/kevin/AV-labels/Results/R/hierarchical_clustering.R'], stdout=subprocess.PIPE, stdin=subprocess.PIPE, shell=True) 
process.communicate()#[0] is stdout

一些想法:

  1. 您可能需要考虑使用Rscript前端,这使得运行脚本更容易; 您可以直接将脚本文件名作为参数传递,而不需要通过标准输入读取脚本。
  2. 您不需要shell只将标准输出重定向到文件,您可以直接使用subprocess.Popen执行此操作。

例:

import subprocess

output_name = 'something'
script_filename = 'hierarchical_clustering.R'
param_filename = '%s_DM_Instances_R.csv' % output_name
result_filename = '%s_out.txt' % output_name
with open(result_filename, 'wb') as result:
    process = subprocess.Popen(['Rscript', script_filename, param_filename],
                               stdout=result);
    process.wait()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM