【问题标题】:Executing Python Script with PHP Variables使用 PHP 变量执行 Python 脚本
【发布时间】:2013-11-05 04:04:36
【问题描述】:

我正在编写一个简单的应用程序,它使用来自表单的信息,通过 $_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文件中echo 'python wordgame2.py $start_word $end_word'时你看到了什么?
  • 添加该行后,它现在输出: 起始词:狗 结束词:cat 结果来自 wordgame.py... python wordgame2.py dog cat 参数数量:1 个参数。参数列表:['wordgame2.py']
  • 我认为错误在于$output = passthru('python wordgame2.py $start_word $end_word'); 试试这个$output = passthru('python wordgame2.py '.$start_word." ".$end_word); 也许,python 由于 $ 关键字而拒绝参数(或者可能 $ 正在调用 shell 进行变量替换)

标签: php python forms variables python-2.7


【解决方案1】:

更新 -

现在我知道了 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不太熟悉(一点也不熟悉),所以只有我的答案以我认为...开头
  • 另外,在连接时传入的两个参数上使用escapeshellarg() 可能很好。
【解决方案2】:

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

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

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

【讨论】:

  • 不要发布你的答案,这是ashish的答案,请接受他的答案。
  • 我在看到他的回答之前已经发布了这个。请查看时间戳。
  • 实际上,我在 7 秒前回答了 :) 否决票是不必要的/未经验证的。
【解决方案3】:

如果我理解你想传递大量的文本,比如某物的内容,那么正确的方法是;

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

【讨论】:

    猜你喜欢
    • 2013-09-15
    • 2019-04-06
    • 2018-01-29
    • 2016-11-29
    • 2015-07-11
    • 1970-01-01
    • 1970-01-01
    • 2015-10-26
    相关资源
    最近更新 更多