9

我正在编写一个简单的应用程序,它使用来自表单的信息,通过 $_POST 将其传递给执行 python 脚本并输出结果的 PHP 脚本。我遇到的问题是我的 python 脚本实际上并没有使用传入的参数运行。

process3.php 文件:

<?php
     $start_word = $_POST['start'];
     $end_word = $_POST['end'];
     echo "Start word: ". $start_word . "<br />";
     echo "End word: ". $end_word . "<br />";
     echo "Results from wordgame.py...";
     echo "</br>";
     $output = passthru('python wordgame2.py $start_word $end_word');
     echo $output;
?>

输出:

Start word: dog
End word: cat
Results from wordgame.py...
Number of arguments: 1 arguments. Argument List: ['wordgame2.py']

在 wordgame2.py 的顶部,我有以下内容(用于调试目的):

#!/usr/bin/env python
import sys
print 'Number of arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.argv)

为什么传递的参数数量不 = 3?(是的,我的表单确实正确发送了数据。)

任何帮助是极大的赞赏!

编辑:我可能会补充说,当我明确告诉它开始和结束词时它确实会运行......像这样:

$output = passthru('python wordgame2.py cat dog');
echo $output
4

3 回答 3

17

更新 -

现在我知道了 PHP,错误在于使用单引号'。在 PHP 中,单引号字符串被认为是文字,PHP 不会评估其中的内容。但是,双引号"字符串会被评估,并且会按照您的预期工作。这个 SO answer很好地总结了这一点。在我们的案例中,

$output = passthru("python wordgame2.py $start_word $end_word");

会工作,但以下不会 -

$output = passthru('python wordgame2.py $start_word $end_word');

原始答案 -

我认为错误在于

$output = passthru("python wordgame2.py $start_word $end_word");

尝试这个

$output = passthru("python wordgame2.py ".$start_word." ".$end_word);
于 2013-11-05T04:25:05.733 回答
4

感谢您的贡献。我已经通过这个简单的修复解决了我的问题:

$command = 'python wordgame2.py ' . $start_word . ' ' . $end_word;
$output = passthru($command);

为了让 passthru 正确处理 php 变量,需要在执行之前将其连接到字符串中。

于 2013-11-05T04:25:12.970 回答
0

好吧,如果我理解您想要传递大量文本,例如某些内容,那么正确的方法是;

$output = passthru("python wordgame2.py ".json_encode($end_word)." ".json_encode($start_word));

于 2020-12-26T20:57:08.070 回答