如何从PHP正确运行Python脚本
我有一个python脚本,我想从PHP运行。这是我的PHP脚本:如何从PHP正确运行Python脚本,php,python,linux,shell,command-line,Php,Python,Linux,Shell,Command Line,我有一个python脚本,我想从PHP运行。这是我的PHP脚本: $data = array('as', 'df', 'gh'); // Execute the python script with the JSON data $result = shell_exec('python /path/to/myScript.py ' . escapeshellarg(json_encode($data))); // Decode the result $resultData = json_dec
$data = array('as', 'df', 'gh');
// Execute the python script with the JSON data
$result = shell_exec('python /path/to/myScript.py ' . escapeshellarg(json_encode($data)));
// Decode the result
$resultData = json_decode($result, true);
// This will contain: array('status' => 'Yes!')
var_dump($resultData);
这是我的Python脚本:
import sys, json
# Load the data that PHP sent us
try:
data = json.loads(sys.argv[1])
except:
print "ERROR"
sys.exit(1)
# Generate some data to send to PHP
result = {'status': 'Yes!'}
# Send it to stdout (to PHP)
print json.dumps(result)
我希望能够在PHP和Python之间交换数据,但上面的错误给出了输出:
错误空值
我哪里做错了
:EDIT:
我运行了以下命令:
$data = array('as', 'df', 'gh');
// Execute the python script with the JSON data
$temp = json_encode($data);
$result= shell_exec('C:\Python27\python.exe test.py ' . "'" . $temp . "'");
echo $result;
在我的机器上,没有JSON对象可以被解码,代码工作正常,显示:
array(1) {
'status' =>
string(4) "Yes!"
}
另一方面,您可以进行一些更改来诊断机器上的问题
python
来实现这一点。如果您看到以下内容:
Python 2.7.6(默认,2014年3月22日,22:59:56)
[GCC 4.8.2]关于linux2
有关详细信息,请键入“帮助”、“版权”、“信用证”或“许可证”。
>>>
你很好。如果您看到您正在运行Python3,这可能是一个问题,因为您的Python脚本是为Python2编写的。因此:
Python 3.4.0(默认,2014年4月11日,13:05:11)
[...]
应该是个线索python myScript.py“[\“as\”、\“df\”、\“gh\”]”
。你看到了什么
{"status": "Yes!"}
很酷。另一个响应表明问题可能与Python脚本有关/path/to/
?那么/path/to/myScript.php
呢
将PHP代码替换为:
<?php
echo file_get_contents("/path/to/myScript.php");
?>
现在运行脚本:
cd /path/to
php -f demo.php
这就是我得到的:
运行命令:python/path/to/myScript.py'[“as”、“df”、“gh”]
得到以下结果:
{“状态”:“是!”}
结果转化为:
阵列(1){
“状态”=>
字符串(4)“是!”
}
你的应该是不同的,并包含一个关于正在发生的事情的提示我通过在论点周围加引号使它起作用! 像这样:
但我想从PHP@harvey_slash:我不确定您的评论与我的答案有何关联。我如何从php运行python myScript.py“[\“as\”,“df\”,“gh\”]?@harvey\u slash:对不起,我的答案不清楚。我重新编写了它。用php运行,你的方式,它可以工作。但是如何让它从json_encode()开始工作?对我来说似乎不起作用:/如果你尝试将数据变量打印回PHP而不是结果var,这会使它产生任何结果吗?var_dump给出了这样的结果:数组(3){[0]=>string(2)“作为”[1]=>string(2)“df”[2]=>string(2)“gh”}如果你有这个问题的解决方案,你能分享吗