【问题标题】:Calling R script from Python从 Python 调用 R 脚本
【发布时间】:2015-03-05 00:04:10
【问题描述】:

我用 Python 编写脚本。我想用 R 绘制一些图表。

运行以下代码时出现错误

import sys
import argparse
import os
import subprocess
parser = argparse.ArgumentParser(description=messg, prog='parser.py', 
    usage='%(prog)s -m [file.txt]')
parser.add_argument('-m', required=True, help='file.txt', type=argparse.FileType('r'))
parser.add_argument('-o', required=True, help='Save output to file', type=argparse.FileType('w'))

args = parser.parse_args()

for ln in args.m:
    prefix, proteins = ln.rstrip().split(':')
    proteins = proteins.split()
    args.o.write('%s\t' % prefix,)
args.o.write('\n')

subprocess.call("Rscript script.r"+args.o, shell=True)

我收到以下错误

Traceback (most recent call last):
  File "parser.py", line 18, in <module>
    subprocess.call("Rscript script.r"+args.o, shell=True)
TypeError: cannot concatenate 'str' and 'file' objects

但是当我从命令行运行它时它可以工作

Rscript script.r file.txt

谁能指出我哪里出错了?

谢谢。

【问题讨论】:

  • 你知道RPy2吗?
  • 感谢您的建议。这很棒。但我卡在 r 中的阅读表上。我想将上述脚本的输出文件用于 R。我在下面添加了代码。非常感谢。

标签: python r python-3.x


【解决方案1】:

type=argparse.FileType('w')) 创建一个文件对象,因此您尝试将字符串连接到文件对象,如果您希望将输出写入文件,您可以将文件对象传递给 subprocess 并让它直接将标准输出写入文件。

subprocess.check_call(["Rscript script.r"],stdout=args.o)

`

【讨论】:

  • 我想先将输出写入文件,然后将文件传递给 Rscript。
【解决方案2】:

正如@padraic-cunningham 的回答所指出的,参数是一个文件对象。使用它的路径:

from rpy2.robjects.packages import importr
utils = importr('utils')

# close the file (in case we are on Windows)
args.m.close()
tbl = base.read_table(args.m.name,sep='\t')
grdevices=importr('grDevices')
grdevices.png(file="Plot.png", width=512, height=512)
r.plot(tbl[1], tbl[2], xlab= "x", ylab= "y")
grdevices.dev_off()

【讨论】:

    猜你喜欢
    • 2014-08-24
    • 1970-01-01
    • 2018-03-20
    • 1970-01-01
    • 1970-01-01
    • 2012-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多