php - 使用 PHP 变量执行 Python 脚本

标签 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;
?>

输出:

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/

相关文章:

php - 如何在嵌套集合模型中插入数据(MySQL);

python - 将 (x, y) 坐标转换为 (x, y, z) 以移动机器人 ARM

php - 用php上传图片到数据库

javascript - 提交表单后我必须刷新我的 php 页面以执行代码并显示输出

php - Doctrine2/Symfony2 : One-Way Many-to-Many Query with Left Join

php - 将模型数据从 Controller 传递到 View joomla 3.1

python - 计算文本文件中的每个单词并输出成本

python - 是否可以在 __post_init__() 或更高版本中卡住数据类对象?

javascript - 如何知道表单输入是否为空(React Hooks)

php - 用js操作php生成的xml元素!