简体   繁体   English

从bash脚本中生成并执行R,Python等脚本

[英]Generate and execute R, Python, etc.., script from within bash script

I have been trying to find a solution for this for a while but haven't found anything satisfactory yet. 我一直试图找到一个解决方案一段时间,但还没有找到任何令人满意的。 I write a lot of bash scripts, but sometimes I want to use R or Python as part of the script. 我编写了很多bash脚本,但有时我想使用R或Python作为脚本的一部分。 Right now, I end up having to write two scripts; 现在,我最终不得不写两个脚本; the original bash script to perform the first half of the task, and the R or Python script to perform the second half of the task. 原始bash脚本执行任务的前半部分,而R或Python脚本执行后半部分任务。 I call the R/Python script from within the bash script. 我在bash脚本中调用R / Python脚本。

I am not satisfied with this solution because it splits my program over two files, which increases the chances of things getting out of sync, more files to track, etc.. Is there a way to write a block of text that contains the entirety of my R/Python script, and then have bash spit it out into a file and pass arguments to it & execute it? 我对这个解决方案不满意,因为它将我的程序分成两个文件,这增加了事情不同步的机会,更多的文件跟踪等等。有没有办法写一个包含整个文件的文本块我的R / Python脚本,然后将bash吐出到一个文件中并将参数传递给它并执行它? Is there an easier solution? 有更简单的解决方案吗? This is more complicated than passing simple one-liners to R/Python because it usually involves creating and manipulating objects over several steps. 这比将简单的单行传递给R / Python更复杂,因为它通常涉及通过几个步骤创建和操作对象。

There are probably lots of solutions, but this one works: 可能有很多解决方案,但这个有效:

#!/bin/bash
## do stuff
R --slave <<EOF
  ## R code
  set.seed(101)
  rnorm($1)
EOF

If you want the flexibility to pass additional bash arguments to R, I suggest: 如果你想灵活地将额外的bash参数传递给R,我建议:

#!/bin/bash
## do stuff
R --slave --args $@ <<EOF
  ## R code
  set.seed(101)
  args <- as.numeric(commandArgs(trailingOnly=TRUE))
  do.call(rnorm,as.list(args))
EOF
  • this allows a flexible number of arguments, but assumes they will all be numeric 这允许灵活数量的参数,但假设它们都是数字的
  • it also assumes that all parameters will be passed through from the bash script to the R sub-script 它还假设所有参数都将从bash脚本传递到R子脚本

obviously you could relax these, eg refer to parameters positionally 显然你可以放松这些,例如在位置参考参数

Here's an example for python, similar to Ben Bolker 's answer 这是python的一个例子,类似于Ben Bolker的回答

#!/bin/bash
python << EOF
print 'Hello $1'
EOF

output: 输出:

> sh test.sh "world"

Hello world

----------------------------------------------- -----------------------------------------------

You can pass variables from bash to python too: 你也可以将变量从bash传递给python:

for ((i=1;i<=$1;i++)) do
python << EOF
print 'Hello world $i times'
EOF
done

output: 输出:

> sh test.sh 5

Hello world 1 times
Hello world 2 times
Hello world 3 times
Hello world 4 times
Hello world 5 times

Importing pandas, numpy, matplotlib, and others for normal jobs works fine. 为正常工作导入pandas,numpy,matplotlib和其他工作正常。

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

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