问题描述
我正在编写一个简单的应用程序,它使用表单中的信息,通过 $_POST 将其传递给执行 python 脚本并输出结果的 PHP 脚本.我遇到的问题是我的 python 脚本实际上并没有在传入参数的情况下运行.
I am writing a simple application that uses information from a form, passes it through $_POST to a PHP script that executes a python script and outputs the results. The problem I am having is that my python script is not actually running with the arguments being passed in.
process3.php 文件:
process3.php file:
<?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 顶部,我有以下内容(用于调试目的):
At the top of my wordgame2.py, I have the following (for debugging purposes):
#!/usr/bin/env python
import sys
print 'Number of arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.argv)
为什么传递的参数数量不是 3?(是的,我的表单确实正确发送了数据.)
Why isn't the number of arguments being passed = 3?(Yes, my form does send the data correctly.)
非常感谢任何帮助!
我可能会补充说,当我明确告诉它开始和结束词时,它确实会运行......像这样:
I might add that it does run when I explicitly tell it the start and end word... something like this:
$output = passthru('python wordgame2.py cat dog');
echo $output
推荐答案
更新 -
既然我知道 PHP,错误在于使用单引号 '
.在 PHP 中,单引号字符串被视为文字,PHP 不会评估其中的内容.但是,双引号 "
字符串会被评估,并且会按照您的预期工作.这在 中有很好的总结这个 SO 答案.在我们的例子中,
Now that I am aware of PHP, the mistake lies in using the single-quotes '
. In PHP, single quoted strings are considered literals, PHP does not evaluate the content inside it. However, double quoted "
strings are evaluated and would work as you are expecting them to. This is beautifully summarized in this SO answer. In our case,
$output = passthru("python wordgame2.py $start_word $end_word");
会工作,但以下不会 -
would work, but the following won't -
$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 变量执行 Python 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!