如何将Python脚本的输出传递给Rscript?

2 投票
1 回答
1182 浏览
提问于 2025-04-18 07:45

我正在写一个bash脚本,这个脚本会从命令行获取一个参数,然后把这个参数传递给一个python脚本。这个python脚本会使用csv.writer模块生成一个.csv文件。接着,我又写了一个R脚本,这个R脚本可以单独接受一个.csv文件,但我现在想把这个.csv文件直接从我的python脚本传给我的R脚本。

这是我的bash脚本:

#!/bin/bash

python protparams.py $1 | Rscript frequency.r

这是我的python脚本:

from Bio import SeqIO
from Bio.SeqUtils import ProtParam
from Bio.SeqUtils import ProtParamData
import sys
import csv

handle = open(sys.argv[1])
with open('test.csv', 'w') as fp: 
    writer = csv.writer(fp, delimiter=',')
    for record in SeqIO.parse(handle, "fasta"): 
            seq = str(record.seq)
            X = ProtParam.ProteinAnalysis(seq)
            data = [seq,X.get_amino_acids_percent(),X.aromaticity(),X.gravy(),X.isoelectric_point(),X.secondary_structure_fraction(),X.molecular_weight(),X.instability_index()]
            writer.writerow(data)

到这里一切都很好,我的python脚本在通过bash脚本调用时能成功生成csv文件,太棒了!但是当我把它直接传给下面的R脚本时,就出现了这个错误:

Error in file(file, "rt") : cannot open the connection
Calls: read.csv -> read.table -> file
In addition: Warning message:
In file(file, "rt") : cannot open file 'NA': No such file or directory
Execution halted

这是我的R脚本,供参考:

args <- commandArgs(trailingOnly = TRUE)
dat <- read.csv(args[1], header=TRUE)
write.csv(dat, file = "out2.csv")

(目前我的R脚本只是测试能否输出这个.csv文件)。

这个错误通常是因为文件不存在,不过在这种情况下,我觉得出现这个错误是因为我的R脚本期待一个作为命令行参数传入的文件,但我现在写的bash脚本并没有以这种方式传递文件。难道我错了,认为把python程序的输出直接传给R脚本和把输出作为命令行参数使用是一样的吗?

非常感谢。

1 个回答

2

是的,只需对 frequency.R 进行一点小改动(从 stdin 读取数据),就可以复制一个 .csv 文件:

l@np350v5c:~$ cat foo.sh 
cat gbr_Country_en_csv_v2.csv | Rscript frequency.R

l@np350v5c:~$ cat frequency.R 
f <- file("stdin")
dat <- read.csv(f, header=TRUE)
write.csv(dat, file = "out2.csv")

撰写回答