在python中使用文件php并使用或打印变量配置

时间:2014-09-06 10:09:30

标签: php python variables

我需要在python应用程序中使用文件config.php,例如文件config.php:

define('DB_USER', 'username');
define('DB_PASSWORD', 'password');
define('DB_HOST', 'localhost');

如何在python中导入此设置并使用它?如何提取用户名,密码和主机?

1 个答案:

答案 0 :(得分:0)

使用 PhpConfig 类来解析数据。

import re

class PhpConfig:
    def __init__(self, config_filename):
        self.defines = {}
        with open(config_filename) as infile:
            for ln in infile:
                match = re.findall('^define\(\'([A-Za-z_0-9]+)\', ?\'(.*)\'', ln)
                if len(match):
                    self.defines[match[0][0]] = match[0][1]

php_config = PhpConfig('config.php')

# Printing define dictionary
print(php_config.defines)

# Accessing just DB_USER
print(php_config.defines['DB_USER'])