在PHP中执行Python脚本并在两者之间交换数据


executing Python script in PHP and exchanging data between the two

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

我有一个类,废料网站的数据在一定的全球方式。我想让它变得更加具体,已经有特定于几个网站的python脚本。

我正在寻找一种方法来合并那些在我的类。

两者之间安全可靠的数据传输是可能的吗?如果是这样的话,让这样的东西运行起来有多难呢?

一般可以使用通用语言格式进行语言间通信,使用stdinstdout进行数据通信。

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)

您正在寻找"进程间通信"(IPC) -您可以使用类似XML-RPC的东西,它基本上允许您在远程进程中调用函数,并处理语言之间所有参数数据类型的转换(因此您可以从Python调用PHP函数,反之亦然-只要参数是受支持的类型)

Python有一个内置XML-RPC服务器和一个客户端

phpxmlrpc库有客户端和服务器

有两个示例,Python服务器和客户端,PHP客户端和服务器

只是有同样的问题,想分享我的解决方案。(紧跟Amadan的建议)

<<h2> python块/h2>
import subprocess
output = subprocess.check_output(["php", path-to-my-php-script, input1])

你也可以这样做:blah = input1而不是只提交一个未命名的参数…然后使用$_GET['blah']。

php块

$blah = $argv[1];

if( isset($blah)){
    // do stuff with $blah
}else{
    throw new 'Exception('No blah.');
}

最好的方法是将python作为子进程运行并捕获其输出,然后对其进行解析。

$pythonoutput = `/usr/bin/env python pythoncode.py`;

使用JSON可能有助于简化两种语言的生成和解析,因为它是标准的,两种语言都支持它(好吧,至少非旧版本支持)。在Python中,

json.dumps(stuff)

然后在PHP中

$stuff = json_decode($pythonoutput);

您还可以显式地将数据保存为文件,或者使用套接字,或者根据您需要的确切场景,有许多不同的方法使其更有效(更复杂),但这是最简单的。

对我来说,escapeshellarg(json_encode($data))给出的不是json格式的字符串,而是像{name: Carl, age: 23}这样的东西。所以在python中,我需要.replace(' ', '"')空格来获得一些真正的json,并能够将json.loads(sys.argv[1])投射到它上面。

问题是,当有人输入一个已经有空格的名字时,比如"Ca "