栏目分类:
子分类:
返回
文库吧用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
文库吧 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

让PHP通过打开

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

替代方法是将数据从PHP写入临时文件,然后使用

system
exec
或类似的调用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_valuen";}?>

将此保存为“ test.rb”:

#!/usr/bin/env rubyputs "<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>HTMLpre</h1>').to_s

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

#!/usr/bin/env rubyrequire_relative 'html2markdown'puts HTML2Markdown.new("<h1>#{ ARGF.read }</h1>").to_s

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



转载请注明:文章转载自 www.wk8.com.cn
本文地址:https://www.wk8.com.cn/it/640075.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 wk8.com.cn

ICP备案号:晋ICP备2021003244-6号