[英]Executing Python Script with PHP Variables
我正在编写一个简单的应用程序,它使用表单中的信息,通过 $_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 不会评估其中的内容。 但是,双引号"
字符串会被评估,并且会像您期望的那样工作。这在这个 SO 答案中得到了很好的总结。在我们的例子中,
$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);
感谢你的贡献。 我已经通过这个简单的修复解决了我的问题:
$command = 'python wordgame2.py ' . $start_word . ' ' . $end_word;
$output = passthru($command);
为了让 passthru 正确处理 php 变量,它需要在执行之前连接成字符串。
好吧,如果我理解你想要传递大量文本,比如某物的内容,那么正确的方法是;
$output = passthru("python wordgame2.py ".json_encode($end_word)." ".json_encode($start_word));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.