将数据从php传递给python并获得结果

时间:2017-12-26 16:44:35

标签: php python

我想将数据从php发送到python并进行一些计算。之后我想发送结果。问题是我无法将数据从php发送到python。

python.php 用户名正在运行,但shell_exec或python有问题

<?php
if(isset($_POST["username"])){

    $nick = $_POST["username"];
    echo shell_exec("python new.py '$nick'");
$jsonData = $_POST["prediction" ];
echo $jsonData;
}
?>

new.py 当我运行python时,它打印C:\ wamp \ www \ MLWebsite \ website \ new.py但它应该是参数

import pymysql.cursors
import sys
import urllib2, urllib
import requests

x=sys.argv[0]
print x

我想了解一下因为new.py

结束而发送结果
mydata=[('prediction','BIO')]
mydata=urllib.urlencode(mydata)
path='http://localhost/MLWebsite/website/python.php'    #the url you want to POST to
req=urllib2.Request(path, mydata)
req.add_header("Content-type", "application/x-www-form-urlencoded")
page=urllib2.urlopen(req).read()
print page

我在Firefox中使用Firebug插件,此错误也会显示在网页中。

  


(!)注意:未定义   index:预测在C:\ wamp \ www \ MLWebsite \ website \ python.php上    6 调用堆栈#TimeMemoryFunctionLocation 10.0006245144 {main}().. \ python.php 0

2 个答案:

答案 0 :(得分:2)

我假设您想这样做的原因(即,使用 PhP 与用户交互但让 Python 实际执行处理)是您想利用 Python 语言完成某些任务,但避免不得不为这些任务使用单独的网络框架。

实现它的一种方法(尽管可能不是您想要解决的方法)是让 PhP 将数据写入文本文件,并用分隔符分隔不同的数据块。然后让 PhP 调用 Python 文件,它知道读取文本文件。

在我下面的示例中,Python 写入一个文件,如果需要,PhP 可以打开它,但您也可以采用其他方式。 PhP 可以写入 .txt 文件,Python 可以读取和操作,然后保存到相同或不同的 .txt 文件,PhP 可以打开并呈现结果。

基本上,您使用 .txt 文件作为“内存”。

这是一个例子:

<?php

echo "<h1>This is PhP!</h1>";

$returnedValue = shell_exec('/home/sitename/public_html/pythonFile.py');

echo $returnedValue; //This line may not be needed if there is nothing to return.

echo "<h2> Completed </h2>";

//Once the 'Complete' Above Renders in the Browser You Know that Python Did Whatever it Was Going to Do to the .txt File

//Now, if you want to have PhP Open the .txt File and Display it You Can

?>

#THIS IS PYTHON
#!/usr/bin/env python

file_object = open("NameOfTextFile.txt", "w+")

file_object.write("Hello World!")

file_object.close()

我意识到这个问题很老,但我最近遇到了同样的问题,这就是我试图解决它的方法。希望它可以帮助某人。

答案 1 :(得分:0)

我认为你的问题需要改进。

据我所知,你的python程序正在做你期望的事情。

background1.jpg

所以,如果你的python程序是prining&#39; new.py&#39;当你写下这个问题时,我认为这是预期的行为。为什么您将未经过处理的用户输入传递给系统调用是另一个问题。你为什么要使用系统调用(为什么不用你的python程序设置web服务?)还是一个问题。

我希望这会有所帮助。