将变量从php发送到python

时间:2013-11-12 16:35:43

标签: php python web remote-server

这是我的问题,我需要从php发送一个变量到python脚本,这并不是那么难,但我发现它们不在同一台服务器上。 php文件在服务器A上,可以在server-a.com上访问,python在不同的服务器上,可以在server-b.com上访问。

这是我当前的php和python代码,它们在同一台服务器上时有效:

PHP:      

// Call to the python script test.py with the JSON data
$result = shell_exec('python test.py ' . escapeshellarg(json_encode($data)));

// get data back from python, decode it and display it
$resultData = json_decode($result, true);
//var_dump($resultData);
echo $result;
?>

的Python:

    import sys, json

# Load the data that PHP testv2.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 PHP
print json.dumps(data)

1 个答案:

答案 0 :(得分:0)

由于您在不同的服务器上,您可能希望通过HTTP进行通信。

如果您的代码非常简单,如示例所示,并且永远不会变得更复杂,请考虑通过CGI调用Python。

对于其他任何事情(或者如果你只是喜欢正确地做),可以考虑使用WSGI和Flask这样的框架,它允许你使用url路由系统定义多个端点。