【问题标题】:Supplying argument by exec function in php通过 php 中的 exec 函数提供参数
【发布时间】:2016-12-07 18:23:05
【问题描述】:

我正在使用以下 php 代码来运行 R 语言的脚本。

echo "<form action='rtest1.php' method='get'>";
echo "Number values to generate: <input type='text' name='N' />";
echo "<input type='submit' />";
echo "</form>";

if(isset($_GET['N']))
{
  $N = $_GET['N'];

  // execute R script from shell
  // this will save a plot at temp.png to the filesystem
  $result=array();
  $int='';
  exec("D:\\R-2.14.0\\bin\\Rscript.exe D:\\wamp\\www\\R\\test.R 7 2 1");


}

这是我的 Rscript 的示例代码

args <- commandArgs(TRUE);

    #assign data path
    data_path <- "D:\\wamp\\www\\R";

    #assign valus to the following three percent
    train_per <- args[1];
    test_per <- args[2];
    val_per <- args[3];

我想将值 7,2 和 1 从 php 代码传递给 Rscript

exec("D:\\R-2.14.0\\bin\\Rscript.exe D:\\wamp\\www\\R\\test.R 7 2 1");

那我该怎么做呢。请帮忙

【问题讨论】:

  • 看起来很好(除了外括号),你运行代码的时候有没有报错?如果它是“语法错误,意外的';',那么最有可能导致它的是外括号。
  • 我必须问这个:你为什么不安装RApache?这种方法往往对代码注入友好。 =/

标签: php r command-line-arguments


【解决方案1】:

要在你的 R 脚本中获取不同的参数值,你可以这样做:

myarg <- commandArgs() #get all arguments from console
n <- myarg[length(myarg)] #number of arguments
tmp<-strsplit(n,",") # parsing of the arguments (here the convention to separate the arg is the comma , )

folderPath <- tmp[[1]][1]; # value of the 1st argument
paramPath <- tmp[[1]][2]; # value of the 2nd argument  
dataPath <- tmp[[1]][3]; # value of the 3rd argument

【讨论】:

  • 您的示例 R 脚本的改编应该是这样的:myarg &lt;- commandArgs() #get all arguments from consolen &lt;- myarg[length(myarg)] #number of argumentstmp&lt;-strsplit(n," ") # parsing of the arguments (here the convention to separate the arg is the space)train_per &lt;- as.numeric(tmp[[1]][1]); # value of the 1st argumenttest_per &lt;- as.numeric(tmp[[1]][2]); # value of the 2nd argument val_per &lt;- as.numeric(tmp[[1]][3]); # value of the 3rd argument
【解决方案2】:

您已经完成了,除了您可能希望执行 as.numeric(args[1]) 等以将字符“7”转换为数字 7。

【讨论】:

  • 它仍然无法正常工作。我是否缺少 R 中的任何其他代码行。如果是,我可以尝试从 Dos Prompt 运行此 R 脚本,然后如何
【解决方案3】:

试试下面的代码:

myarg <- commandArgs()

tmp <- strsplit(myarg," ")

arg1 <- tmp[[1]][1]; # value of the 1st argument
arg2 <- tmp[[2]][1]; # value of the 2nd argument  
arg3 <- tmp[[3]][1]; # value of the 3rd argument

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多