littler确定是否按部署运行

时间:2015-02-18 16:24:09

标签: r shebang

我很高兴能找到Jeff和Dirk的应用程序来从终端运行R函数。 ¡荣誉!
从那时起,我已经能够将我的功能传递给我的开发团队,让他们在其他服务器上运行。

我的问题是关于它的部署。在将它传递给其他人之前,我在我的电脑中尝试并用RStudio准备它......(也是赞誉) 我想知道是否有一个命令在脚本中运行,我可以判断该函数是从命令运行还是用R执行它。

感谢。

2 个答案:

答案 0 :(得分:3)

我不知道是否有更小的具体答案。但总的来说,R中不可能(或非常难)确定代码的运行方式,这是我在modules上工作的动机之一。

R知道的唯一事情是代码是否在交互式shell中运行(通过interactive())。

使用模块,您可以测试是否设置module_name(),类似于Python的__name__

if (is.null(module_name()) && ! interactive()) {
    # Stand-alone, execute main entry point
}

if (! is.null(module_name())) {
    # Code is being loaded as a module.
}

我基于此编写了一个small wrapper,我用它来编写命令行应用程序。例如,一个非常简单的cat类应用程序看起来如下:

#!/usr/bin/env Rscript

sys = modules::import('sys')

sys$run({
    if (length(sys$args) == 0) {
        message('Usage: ', script_name(), ' filename')
        sys$exit(1)
    }

    input = sys$args[1]
    cat(readLines(input))
})

答案 1 :(得分:2)

我不确定我理解你的问题。你的意思是

edd@max:~$ which r
/usr/local/bin/r
edd@max:~$ 

您可以将which的结果与空字符串进行比较,因为当您要求不存在的程序时,没有任何内容返回。

edd@max:~$ which s      # we know we don't have this
edd@max:~$ 

然后,您可以使用which r的结果来检查版本:

edd@max:~$ `which r` --version
r ('littler') version 0.2.2

git revision 8df31e5 as of Thu Jan 29 17:43:21 2015 -0800
built at 19:48:17 on Jan 29 2015
using GNU R Version 3.1.2 (2014-10-31)

Copyright (C) 2006 - 2014  Jeffrey Horner and Dirk Eddelbuettel

r is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under the terms of the
GNU General Public License.  For more information about
these matters, see http://www.gnu.org/copyleft/gpl.html.

edd@max:~$ 

编辑:由于您似乎对interactive()的真或假感到困惑,请考虑r --help

edd@max:~$ r --help

Usage: r [options] [-|file]

Launch GNU R to execute the R commands supplied in the specified file, or
from stdin if '-' is used. Suitable for so-called shebang '#!/'-line scripts.

Options:
  -h, --help           Give this help list
      --usage          Give a short usage message
  -V, --version        Show the version number
  -v, --vanilla        Pass the '--vanilla' option to R
  -t, --rtemp          Use per-session temporary directory as R does
  -i, --interactive    Let interactive() return 'true' rather than 'false'
  -q, --quick          Skip autoload / delayed assign of default libraries
  -p, --verbose        Print the value of expressions to the console
  -l, --packages list  Load the R packages from the comma-separated 'list'
  -d, --datastdin      Prepend command to load 'X' as csv from stdin
  -e, --eval  expr     Let R evaluate 'expr'


edd@max:~$ 

edd@max:~$ r -e'print(interactive())'
[1] FALSE
edd@max:~$ r -i -e'print(interactive())'
[1] TRUE
edd@max:~$ 

但是设置而不是查询它。