This article mainly introduces python to process PHP array text files. The PHP array text in this article is a configuration file of multiple redis databases. The requirement is to extract relevant parameters and combine them into Shell commands, for more information, see
Requirements:
Process a configuration file and splice the available characters. The following is the original text. We want to get this result,
The Code is as follows:
Redis-h 127.0.0.1-p 6379 | select 2
Redis-h 127.0.0.1-p 6379 | select 16
Redis-h 127.0.0.1-p 6379 | select 8
Original text:
The Code is as follows:
'Redis _ list' => array (
'Normal' => array (
'Host' => '10. 4.3.125 ',
'Port' => 6405,
'Db' => 6
),
'Redis _ list' => array (
'Normal' => array (
'Host' => '2017. 0.0.1 ',
'Port' => 6379,
'Db' => 2
),
'Redis _ list' => array (
'Normal' => array (
'Host' => '2017. 0.0.1 ',
'Port' => 6379,
'Db' => 16
),
'Redis _ list' => array (
'Normal' => array (
'Host' => '2017. 0.0.1 ',
'Port' => 6379,
'Db' => 8
),
Python:
The Code is as follows:
#! /Usr/bin/env python
# Coding = UTF-8
Import OS
File = open ("redis_list.txt", "r ")
File_content = file. read ()
Php_array = file_content.replace ("'normal' => array (","")
Pstr = php_array.replace ("",""). replace ("\ r ",""). replace ("\ n ",""). replace ("\ t ",""). replace ("(",""). replace ("'",""). replace ("),","")
# Print pstr
Pstr_list = pstr. split ("redis_list => array ")
# Print type (pstr_list)
Cf_param = []
For I in pstr_list:
If I:
# 'Host' => '127. 0.0.1 ', 'Port' => 127, 'db' => 2
I _list = I. split (",")
If len (I _list) = 3:
Op = {};
For ii in I _list:
Ii_list = ii. split ("=> ")
If len (ii_list) = 2:
Op [ii_list [0] = ii_list [1]
Cf_param.append (op)
For I in cf_param:
Print "redis-h" + I ["host"] + "-p" + I ["port"] + "| select" + "" + I ["db"]