使用PHP变量执行Python脚本

Mic*_*cah 8 php python forms variables python-2.7

我正在编写一个使用表单信息的简单应用程序,将其通过$ _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;
?>
Run Code Online (Sandbox Code Playgroud)

输出:

Start word: dog
End word: cat
Results from wordgame.py...
Number of arguments: 1 arguments. Argument List: ['wordgame2.py']
Run Code Online (Sandbox Code Playgroud)

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

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

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

任何帮助是极大的赞赏!

编辑:我可能会补充说,它确实在我明确告诉它开头和结尾字时运行......这样的事情:

$output = passthru('python wordgame2.py cat dog');
echo $output
Run Code Online (Sandbox Code Playgroud)

sha*_*k3r 15

更新 -

现在我知道PHP,错误在于使用单引号'.在PHP中,单引号字符串被视为文字,PHP不评估其中的内容.但是,双引号"字符串会被评估,并且可以按照您的预期工作.在这个SO答案中,这是精美的总结.在我们的例子中,

$output = passthru("python wordgame2.py $start_word $end_word");
Run Code Online (Sandbox Code Playgroud)

会工作,但以下不会 -

$output = passthru('python wordgame2.py $start_word $end_word');
Run Code Online (Sandbox Code Playgroud)

原始答案 -

我认为错误在于

$output = passthru("python wordgame2.py $start_word $end_word");
Run Code Online (Sandbox Code Playgroud)

试试这个

$output = passthru("python wordgame2.py ".$start_word." ".$end_word);
Run Code Online (Sandbox Code Playgroud)