在 PHP 中执行 Python 脚本并在两者之间交换数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14047979/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
executing Python script in PHP and exchanging data between the two
提问by Neta Meta
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 ?
两者之间安全可靠的数据传输是否可能?如果是这样,让这样的事情发生有多困难?
采纳答案by Tom van der Woerdt
You can generally communicate between languages by using common language formats, and using stdinand stdoutto communicate the data.
您通常可以使用通用语言格式在语言之间进行通信,并使用stdin和stdout来通信数据。
Example with PHP/Python using a shell argument to send the initial data via JSON
使用 shell 参数通过 JSON 发送初始数据的 PHP/Python 示例
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:
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)
回答by Amadan
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). In Python,
使用 JSON 可能有助于在两种语言中轻松生成和解析,因为它是标准的并且两种语言都支持它(好吧,至少非古代版本支持)。在 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.
您还可以将数据显式保存为文件,或使用套接字,或者根据您需要的具体场景,使用许多不同的方法来提高效率(也更复杂),但这是最简单的。
回答by dbr
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 serverand a client
Python 有一个内置的XML-RPC 服务器和一个客户端
The phpxmlrpclibrary has both a client and server
该PHPXMLRPC库有一个客户端和服务器
There are examples for both, Python server and client, and a PHP clientand server
回答by fchaubard
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.');
}

