在PHP中执行Python脚本并在两者之间交换数据 [英] executing Python script in PHP and exchanging data between the two

查看:86
本文介绍了在PHP中执行Python脚本并在两者之间交换数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在PHP中运行Python脚本并相互传递变量?

Is it possible to run a Python script within PHP and transferring variables from each other ?

我有一堂课,以某种全球性的方式抓取网站以获取数据.我想使其更加具体,并且已经具有针对多个网站的pythons脚本.

I have a class that scraps websites for data in a certain global way. i want to make it go a lot more specific and already have pythons scripts specific to several website.

我正在寻找一种将这些内容纳入班级的方法.

I am looking for a way to incorporate those inside my class.

两者之间安全可靠的数据传输是否可能?如果是这样的话,要取得这样的成就有多困难?

Is safe and reliable data transfer between the two even possible ? if so how difficult it is to get something like that going ?

推荐答案

通常,您可以通过使用通用语言格式以及使用stdinstdout进行数据通信来在语言之间进行通信.

You can generally communicate between languages by using common language formats, and using stdin and stdout to communicate the data.

PHP/Python示例,其中使用shell参数通过JSON发送初始数据

PHP:

// This is the data you want to pass to Python
$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脚本并在两者之间交换数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆