如何从PHP代码运行ruby文件

时间:2016-08-31 07:58:00

标签: php ruby-on-rails ruby windows-server-2012-r2

尝试了这些命令

exec("ruby helloword.rb");
system ("ruby helloword.rb");

在Windows服务器2012R2上运行php 我只是想要运行ruby类,因为它将从文本文件中读取和写入结果,而不是我可以使用这些文本文件。 有没有简单的方法来完成这项工作。 在stackoverflow上尝试了几乎所有的东西。所以请不要将此标记为重复。

3 个答案:

答案 0 :(得分:1)

我不确定这是否是你要找的,但见下文:)

以下示例:

<?php
$descriptorspec = array(
   0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
   1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
   2 => array("file", "./error-output.txt", "a") // stderr is a file to write to
);
$process = proc_open('ruby ./test.rb', $descriptorspec, $pipes);

if (is_resource($process)) {
    // $pipes now looks like this:
    // 0 => writeable handle connected to child stdin
    // 1 => readable handle connected to child stdout
    // Any error output will be appended to /tmp/error-output.txt

    fwrite($pipes[0], 'hello world');
    fclose($pipes[0]);

    echo stream_get_contents($pipes[1]);
    fclose($pipes[1]);

    // It is important that you close any pipes before calling
    // proc_close in order to avoid a deadlock
    $return_value = proc_close($process);

    echo "command returned $return_value\n";
}
?>

另存为 将其保存为“test.php”:

源:

Run Ruby/Python from PHP Code

这是另一个很好的例子:

//PHP script to execute ruby scripts when the host doesn't have a cgi handler for .rb
//Use with this .htaccess:

/*
Options +FollowSymlinks
RewriteEngine on
RewriteRule ^(.*)\.rb$ handler.php?rb=$1.rb [NC,QSA]
*/

$file = $_GET['rb'];

if(in_array($file, scandir('.')))
{
foreach($_REQUEST as $key=>$value) if($key != 'rb') $args .= " $key=".urlencode($value);
echo exec(escapeshellcmd('./'.$file.$args));
}
else
{
echo '404- Page not found';
}
?>

此致

丹尼尔

答案 1 :(得分:0)

通过添加exec("filename");起作用 之前写的就像这个exec(&#39; ruby​​ filename&#39;); 非常感谢大家的回复。

答案 2 :(得分:-1)

您可以使用load的{​​{1}}方法。请参阅http://ruby-doc.org/core-2.2.1/Kernel.html#method-i-load

上的文档