使用 python 读取 php 文件的输出
read output of php file using python
我在服务器上有一个 php
文件,它以 json
格式打印来自 mysql
数据库的一些数据。
当我在浏览器中 运行 我的 php
文件时,我可以看到 json
数组。现在我想在 python
文件中获取 json
数组。有办法吗?
这是我正在使用的代码
import subprocess
import json
import codecs
proc = subprocess.Popen("http://www.rpi-connect.esy.es/getappliances?room=1", shell=True, stdout=subprocess.PIPE)
script_response = str(proc.stdout.read().decode('utf8'))
print(script_response)
运行 使用以下命令的代码并将其标准输出存储到变量中:
import subprocess
proc = subprocess.Popen("php /path/to/your/script.php", shell=True, stdout=subprocess.PIPE)
script_response = proc.stdout.read()
如果您在 json 中也需要 python 中的数据:
import json
data = json.loads(script_response)
您可以通过让 PHP 脚本将 JSON 输出到服务器上的文件,然后让 python 脚本从中读取 JSON 来实现此目的文件。
你可以这样实现:
PHP 脚本:
<?php
$json = json_encode('your data');
$file = '/tmp/json-file';
file_put_contents($file, $json);
Python 脚本:
import json
with open('/tmp/json-file') as data_file:
data = json.load(data_file)
# do whatever you need to do with data here
在尝试了很多不同的 python 库后我终于得到了答案
import json
import urllib.request
url = "http://example.com/your-filename.php"
x = urllib.request.urlopen(url)
raw_data = x.read()
encoding = x.info().get_content_charset('utf8') # JSON default
print(raw_data) #this is data in string format
data = json.loads(raw_data.decode(encoding))
print(data) #this would be your json data
这适用于 python 3.4。对于 python 2.7 尝试使用 json.load() 而不是 json.loads()
我在服务器上有一个 php
文件,它以 json
格式打印来自 mysql
数据库的一些数据。
当我在浏览器中 运行 我的 php
文件时,我可以看到 json
数组。现在我想在 python
文件中获取 json
数组。有办法吗?
这是我正在使用的代码
import subprocess
import json
import codecs
proc = subprocess.Popen("http://www.rpi-connect.esy.es/getappliances?room=1", shell=True, stdout=subprocess.PIPE)
script_response = str(proc.stdout.read().decode('utf8'))
print(script_response)
运行 使用以下命令的代码并将其标准输出存储到变量中:
import subprocess
proc = subprocess.Popen("php /path/to/your/script.php", shell=True, stdout=subprocess.PIPE)
script_response = proc.stdout.read()
如果您在 json 中也需要 python 中的数据:
import json
data = json.loads(script_response)
您可以通过让 PHP 脚本将 JSON 输出到服务器上的文件,然后让 python 脚本从中读取 JSON 来实现此目的文件。
你可以这样实现:
PHP 脚本:
<?php
$json = json_encode('your data');
$file = '/tmp/json-file';
file_put_contents($file, $json);
Python 脚本:
import json
with open('/tmp/json-file') as data_file:
data = json.load(data_file)
# do whatever you need to do with data here
在尝试了很多不同的 python 库后我终于得到了答案
import json
import urllib.request
url = "http://example.com/your-filename.php"
x = urllib.request.urlopen(url)
raw_data = x.read()
encoding = x.info().get_content_charset('utf8') # JSON default
print(raw_data) #this is data in string format
data = json.loads(raw_data.decode(encoding))
print(data) #this would be your json data
这适用于 python 3.4。对于 python 2.7 尝试使用 json.load() 而不是 json.loads()