简体   繁体   English

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

[英]executing Python script in PHP and exchanging data between the two

Is it possible to run a Python script within PHP and transferring variables from each other ?是否可以在 PHP 中运行 Python 脚本并相互传输变量?

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.我想让它变得更具体,并且已经有针对多个网站的 python 脚本。

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 ?如果是这样,让这样的事情发生有多困难?

You can generally communicate between languages by using common language formats, and using stdin and stdout to communicate the data. 您通常可以使用通用语言格式在语言之间进行通信,并使用stdinstdout进行数据通信。

Example with PHP/Python using a shell argument to send the initial data via JSON PHP / Python使用shell参数通过JSON发送初始数据的示例

PHP: 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)

You are looking for "interprocess communication" (IPC) - you could use something like XML-RPC, which basically lets you call a function in a remote process, and handles the translation of all the argument data-types between languages (so you could call a PHP function from Python, or vice versa - as long as the arguments are of a supported type ) 您正在寻找“进程间通信”(IPC) - 您可以使用类似XML-RPC的东西,它基本上允许您在远程进程中调用函数,并处理语言之间所有参数数据类型的转换(所以你可以从Python调用PHP函数,反之亦然 - 只要参数是受支持的类型

Python has a builtin XML-RPC server and a client Python有一个内置的XML-RPC服务器和一个客户端

The phpxmlrpc library has both a client and server phpxmlrpc库同时具有客户端和服务器

There are examples for both, Python server and client , and a PHP client and server Python服务器和客户端以及PHP客户端服务器都有示例

The best bet is running python as a subprocess and capturing its output, then parsing it. 最好的办法是将python作为子进程运行并捕获其输出,然后解析它。

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

Using JSON would probably help make it easy to both produce and parse in both languages, since it's standard and both languages support it (well, at least non-ancient versions do). 使用JSON可能有助于在两种语言中轻松生成和解析,因为它是标准的,并且两种语言都支持它(嗯,至少非古代版本)。 In Python, 在Python中,

json.dumps(stuff)

and then in PHP 然后在PHP中

$stuff = json_decode($pythonoutput);

You could also explicitly save the data as files, or use sockets, or have many different ways to make this more efficient (and more complicated) depending on the exact scenario you need, but this is the simplest. 您还可以将数据显式保存为文件,或使用套接字,或者根据您需要的确切方案,使用许多不同的方法来提高效率(并且更复杂),但这是最简单的方法。

Just had the same problem and wanted to share my solution. 刚遇到同样的问题,想分享我的解决方案。 (follows closely what Amadan suggests) (紧跟阿马丹建议的那样)

python piece 蟒蛇片

import subprocess

output = subprocess.check_output(["php", path-to-my-php-script, input1])

you could also do: blah = input1 instead of just submitting an unnamed arg... and then use the $_GET['blah']. 你也可以这样做:blah = input1而不是只提交一个未命名的arg ...然后使用$ _GET ['blah']。

php piece php片

$blah = $argv[1];



if( isset($blah)){

    // do stuff with $blah

}else{
    throw new \Exception('No blah.');
}

For me the escapeshellarg(json_encode($data))<\/code> is giving not exactly a json-formatted string, but something like { name : Carl , age : 23 }.对我来说, escapeshellarg(json_encode($data))<\/code>给出的不完全是一个 json 格式的字符串,而是像 { name : Carl , age : 23 } 这样的东西。 So in python i need to .replace(' ', '"')<\/code> the whitespaces to get some real json and be able to cast the json.loads(sys.argv[1])<\/code> on it.因此,在 python 中,我需要.replace(' ', '"')<\/code>空格来获得一些真正的 json 并能够在其上投射json.loads(sys.argv[1])<\/code> 。

The problem is, when someone enters a name with already whitespaces in it like "Ca rl".问题是,当有人输入一个已经有空格的名字时,比如“Ca rl”。

"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM