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

31

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

我有一个类,可以以某种全局方式从网站上获取数据。我想让它更加具体化,并已经使用了几个特定于网站的Python脚本。

我正在寻找一种将这些脚本合并到我的类中的方法。

两者之间的安全可靠数据传输是否可能?如果可能,那么实现起来有多困难?


可以通过使用命令行(cli)exec()等方法来完成。 - user557846
2
感谢大家的帮助。 - Neta Meta
5个回答

74

您通常可以使用通用语言格式,并使用 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:

->

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)

2
你的 PHP 示例看起来非常简单。 - Neta Meta
1
没有什么难的,不是吗!只要使用标准数据结构(字符串、整数、数组、字典、布尔值、浮点数),这种方法就可以让你传递任何你需要的东西。 - Tom van der Woerdt
4
脚本应该放在哪里呢?我在 PHP 页面中得到了空值! - postgres
it's the same of the answer - postgres
6
如果您在 Python 脚本中遇到 NULL 返回,可能是因为 escapeshellarg() 从编码的 JSON 中去除了双引号,导致 JSON 无效,因此导致 json.loads() 失败。请尝试在 PHP 中使用 base64_encode(); 替代 escapeshellarg();,并且在 Python 中使用 import base64/base64.b64decode()。此外,如果您的路径包含空格,请不要忘记用双引号将其括起来,例如 'python "path/that/has spaces/script.py" ' 就像我的情况一样。祝顺利!:) - Brian
显示剩余4条评论

10

2

我遇到了同样的问题,想要分享我的解决方案。(紧随Amadan的建议)

Python代码片段

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.');
}

0
最好的方法是将Python作为子进程运行并捕获其输出,然后进行解析。
$pythonoutput = `/usr/bin/env python pythoncode.py`;

使用JSON可能会使在两种语言中都易于生成和解析,因为它是标准的,并且两种语言都支持它(至少是非古代版本)。在Python中,

json.dumps(stuff)

然后在PHP中实现

$stuff = json_decode($pythonoutput);

你也可以将数据显式地保存为文件,或使用套接字,或有许多不同的方法使其更有效(和更复杂),具体取决于您需要的确切情况,但这是最简单的方法。

0

对我来说,escapeshellarg(json_encode($data))并没有给出一个完全格式化为json的字符串,而是像这样的东西:{ name : Carl , age : 23 }。 因此,在Python中,我需要使用.replace(' ', '"')替换空格以获取一些真正的JSON,并能够将其转换为json.loads(sys.argv[1])

问题在于,当有人输入一个带有空格的名称,比如“Ca rl”时。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接