【发布时间】:2014-05-27 21:40:12
【问题描述】:
我正在编写一个 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)
到目前为止一切正常我的 python 脚本在通过我的 bash 脚本调用时会生成 csv 文件。伟大的!但是当我像在我的 bash 文件中一样将它通过管道传输到以下 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 脚本的命令行参数是错误的吗?
非常感谢。
【问题讨论】:
-
您可能会发现this answer 很有用...
-
未经测试的建议。如果未设置 sys.argv[1],请使用
fp=sys.stdout。否则,使用fp=open('test.csv', 'w')然后调用不带参数的python 脚本。 -
请参阅stackoverflow.com/a/15785789/1201032,了解如何编写可以从文件或流中读取其输入的 R 脚本。