您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何从PHP内部传递和接收参数来运行Ruby / Python脚本?

如何从PHP内部传递和接收参数来运行Ruby / Python脚本?

PHP通过打开proc_openHTML到脚本中的STDIN来打开Ruby或Python脚本。Ruby / Python脚本读取并处理数据,并通过STDOUT将其返回给PHP脚本,然后退出。这是通过popenPerl,Ruby或Python中的类似功能来执行操作的一种常见方式,它很不错,因为它可以让您访问STDERR,以防万一某些东西大块地散了,不需要临时文件,但这要复杂一些。

替代方法是将数据从PHP写入临时文件,然后使用systemexec或类似的调用Ruby / Python脚本来打开和处理它,并使用其STDOUT打印输出

编辑:

请参阅@Jonke的答案“ Ruby中使用STDIN的最佳实践?”。有关使用Ruby读取STDIN和写入STDOUT有多简单的示例。“您如何从python中的stdin中读取信息”对该语言提供了一些很好的示例。

这是一个简单的示例,显示了如何调用Ruby脚本,如何通过PHP的STDIN管道向其传递字符串以及如何读取Ruby脚本的STDOUT:

将此保存为“ test.PHP”:

<?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.rb”:

#!/usr/bin/env ruby

puts "<b>#{ ARGF.read }</b>"

运行PHP脚本可以得到:

Greg:Desktop greg$ PHP test.PHP 
<b>hello world</b>
command returned 0

PHP脚本正在打开Ruby解释器,后者将打开Ruby脚本。然后,PHP向其发送“ hello world”。Ruby将接收到的文本用粗体标签包装,然后将其输出(由PHP捕获),然后输出。没有临时文件,没有在命令行上传递任何内容,如果需要的话,您可以传递很多数据,而且速度非常快。可以很容易地使用Python或Perl代替Ruby。

编辑:

如果你有:

HTML2Markdown.new('<h1>HTMLcode</h1>').to_s

作为示例代码,那么您可以开始开发具有以下内容的Ruby解决方案:

#!/usr/bin/env ruby

require_relative 'html2markdown'

puts HTML2Markdown.new("<h1>#{ ARGF.read }</h1>").to_s

假设您已经下载了HTML2Markdown代码并将其保存在当前目录中并且正在运行Ruby 1.9.2。

php 2022/1/1 18:44:47 有309人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶