我正在编写一个简单的应用程序,它使用来自表单的信息,通过 $_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
最佳答案
更新 -
现在我了解 PHP,错误在于使用单引号 '
。在 PHP 中,单引号字符串被认为是文字,PHP 不会评估其中的内容。但是,双引号 "
字符串会被评估,并且会按您期望的那样工作。这在 this 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);
关于php - 使用 PHP 变量执行 Python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19781768/