一个例子是R计算器,可以调用,例如rcalc.R "log(10*2)"
:
#!/usr/bin/Rscript
# rcalc.R, an example R calculator
# Create evaluation environment without predefined functions
myenv = new.env(parent=emptyenv())
# Define names of R functions which are allowed for calculation
allowedFunctions = c("+", "-", "*", "/", "^","exp", "log")
# Assign the functions to the evaluation environment
for(name in allowedFunctions){
assign(name,match.fun(name), envir=myenv)
}
# Read in a user command ...
userCommand=commandArgs(TRUE)[1]
# ... parse it, execute it and print it.
eval(parse(text=userCommand),envir=myenv)
示例:
rcalc.R "log(10*10)"
## [1] 3
rcalc.R "list.files('.')"
## Fehler in eval(expr, envir, enclos) :
## konnte Funktion "list.files" nicht finden
## Ruft auf: eval -> eval
## Ausführung angehalten
rcalc.R "library('base')"
## Fehler in eval(expr, envir, enclos) :
## konnte Funktion "library" nicht finden
## Ruft auf: eval -> eval
## Ausführung angehalten
是否可以通过脚本的命令行输入中断此沙箱以执行任意代码?
我的动机是绘图脚本,它允许用户在输入数据只读一次时打印出多个图。他们的想法是能够在命令行上指定自定义绘图命令,以及从cut
,as.factor
等派生的一些简化数据重新格式化命令。