Python compare configuration files

The most common job profiles, there are four: key = value of the common configuration file, Json formatted configuration file, HTML file format configuration and YMAML profile.

Among the first to the majority, the latter three are more common in mature open source products, this article only for the first profile.

Provides general Linux shell diff command to compare the class of plain text configuration files, Python's difflib also provides a comparison str and HTML interfaces, but the actual project these tools actually not easy, mainly because of our configuration standardization of files are not unified.

In order to solve such problems, it is best to write specific configuration file comparison tool for a specific project, so that when the release will be very useful.

Other words lazy to say, directly attached to the code:

! # / usr / bin / Python 
# Coding = UTF-8 

'' ' 
This script is adapted to compare the profile key = value format 
to use way: 
config_match.py old_file new_file 
will eventually be added to the new configuration item in new_file old_file in, old_file in the existing configuration items do not make any changes. 
'' ' 

Import Re 
Import OS, SYS 
reload (SYS) 
sys.setdefaultencoding ( "UTF-. 8") 

old_file the sys.argv = [. 1] 
new_file = the sys.argv [2] 

DEF list2dict (File): 
    with Open (File, 'R & lt') AS F: 
    	List f.readlines = () 
    # traversing str list, and exclude blank lines starting with # str, str elements used to split into [k, v] element 
    for e in list [0:] : 
    	IF re.match ( '^ #', E) or re.match ( '^ $', E): 
	    list.remove (E) 
    I = 0 
    for E in List: 
	e_split = e.strip () Split ( '='. 
	IF len (e_split) == 2: 
	    . K, V = e.strip () Split ( '=') 
    	    List [I] = [K, V] 
	the else : 
	    Pass 
	I = I +. 1 
    # to this list becomes the [[k, v], [ k, v], ...] this list 
    CI = # comprises or contains a plurality of number = number will be ignored, this is to be noted that 
    return dict (List) 

old_dict = list2dict (old_file) 
new_dict = list2dict (new_file) 

'' ' 
to traverse the new configuration file, add conf_need_added {} was added configuration item dictionary, then the dictionary to conf_need_added {} k = v append the old file format. 
If duplicate key values need to be updated would be too simple, dict type comes with the update () method can be very good to complete the task, so no need to toss. 
'' ' 
Conf_need_added = {} 
for K, V in new_dict.items (): 
    IF K Not in old_dict.keys (): 
		conf_need_added [K] V = 
    the else: 
		Pass

Open with (old_file, 'A') AS F: 
    for K, V in conf_need_added.items ():
		f.write ( '\ n # Here is the new configuration items: \ n-') 
		f.write (STR (K) + '=' + STR (V) + '\ n-')

 

Guess you like

Origin www.cnblogs.com/leohahah/p/10984574.html