скажем, мы хотим сделать python config reader от php.
config.php
$arr = array(
'a config',
'b config',
'c config => 'with values'
)
$arr2 = array(
'a config',
'b config',
'c config => 'with values'
)
readconfig.py
f = open('config.php', 'r')
// somehow get the array then turns it into pythons arr1 and arr2
print arr1
# arr1 = {'a config', 'b config', 'c config': 'with values'}
print arr2
# arr2 = {'a config', 'b config', 'c config': 'with values'}
возможно ли это в python?
from subprocess import check_output
import json
config = check_output(['php', '-r', 'echo json_encode(include "config.php");'])
config = json.loads(config)
где config.php
возвращает массив:
return [
'param1' => 'value1',
'param2' => 'value2',
];
Parse config usin PHP скрипт
Сохранить конфиг vars в файл с помощью JSON
Выполнить парсер из Pytson с помощью os.system()
Чтение файла JSON в Python
Как вариант Eugenes:
В моей ситуации файл php задавал только переменные, он не возвращал массив.
Таким образом, я должен был выполнить включение перед json_encode; затем закодировать определенные переменные. Это было для чтения version.php для ownCloud. См. Https://github.com/owncloud/core
Например
vFileName=configDict['ocDir']+'/version.php'
cmd=['/usr/bin/php','-r','include "'+vFileName+'"; echo json_encode(array($OC_Version,$OC_VersionString));']
ocVersion, ocVersionString=json.loads(subprocess.check_output(cmd))
key=value
.