python - 如何将 python 脚本的输出传输到 Rscript 中?

标签 python linux r bash pipe

我正在编写一个 bash 脚本,它使用命令行输入中的参数传递到 python 脚本中,结果是使用 python 的 csv.writer 模块生成 .csv 文件。然后,我编写了一个 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)

到目前为止一切正常当通过 bash 脚本调用时,我的 python 脚本会生成 csv 文件。伟大的!但是当我将其通过管道传输到以下 R 脚本(如我的 bash 文件中)时,出现此错误:

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 脚本的命令行参数相同?

非常感谢。

最佳答案

是的,频率.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")

关于python - 如何将 python 脚本的输出传输到 Rscript 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23899439/

相关文章:

r - 使用 dplyr 包 R 改变 data.frame 或 tibble 中的选定列

python - 保护多线程程序中的关键部分

python - 修改Keras中的图层参数

Python lxml : Ignore XML declaration (errors)

r - 使用data()从 "R"包中加载数据集,直接赋值给一个变量?

r - 将 R 字符公式转换为数字

python : call ffmpeg command line with subprocess

c++ - 使用 C/C++ 和 LibSerial 在 Ubuntu 中的串行端口上读取和写入

linux - 不使用脚本设置 VCAP (cloudfoundry)

linux - 在 Linux 中使用 PAM 进行身份验证。为什么某些用户可能无法运行?