将JSON数据从PHP传递到Python脚本 [英] Pass JSON Data from PHP to Python Script

查看:139
本文介绍了将JSON数据从PHP传递到Python脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够将PHP数组传递给Python脚本,该脚本将利用数据执行一些任务.我想尝试使用shell_exec()从PHP执行我的Python脚本,并将JSON数据传递给它(这是我的新手).

I'd like to be able to pass a PHP array to a Python script, which will utilize the data to perform some tasks. I wanted to try to execute my the Python script from PHP using shell_exec() and pass the JSON data to it (which I'm completely new to).

$foods = array("pizza", "french fries");
$result = shell_exec('python ./input.py ' . escapeshellarg(json_encode($foods)));
echo $result;

"escapeshellarg(json_encode($ foods)))"函数似乎将我的数组传递给Python脚本,如下所示(如果我回显"该函数,则会得到此值:

The "escapeshellarg(json_encode($foods)))" function seems to hand off my array as the following to the Python script (I get this value if I 'echo' the function:

'["pizza","french fries"]'

然后在Python脚本中:

Then inside the Python script:

import sys, json
data = json.loads(sys.argv[1])
foods = json.dumps(data)
print(foods)

这会将以下内容输出到浏览器:

This prints out the following to the browser:

["pizza", "french fries"]

这是一个普通的旧字符串,而不是列表.我的问题是,如何最好地将这些数据视为列表或某种可以用,"作为定界符进行迭代的数据结构?我并不是真的想要将文本输出到浏览器,我只是想能够将列表分解成几部分,然后将它们插入文件系统上的文本文件中.

This is a plain old string, not a list. My question is, how can I best treat this data like a list, or some kind of data structure which I can iterate through with the "," as a delimiter? I don't really want to output the text to the browser, I just want to be able to break down the list into pieces and insert them into a text file on the filesystem.

推荐答案

遇到相同的问题

让我告诉你我做了什么

PHP:

base64_encode(json_encode($bodyData))

然后

json_decode(shell_exec('python ' . base64_encode(json_encode($bodyData)) );

在Python中,我有

and in Python I have

import base64

content = json.loads(base64.b64decode(sys.argv[1]))

Em L已经提到过:)

as Em L already mentioned :)

对我有用 干杯!

这篇关于将JSON数据从PHP传递到Python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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