码迷,mamicode.com
首页 > 其他好文 > 详细

difflib模块

时间:2020-06-10 18:51:32      阅读:53      评论:0      收藏:0      [点我收藏+]

标签:版本   image   版本控制   gif   users   one   var   form   rem   

difflib可比对文本之间的差异,支持输出为HTML文档,与Linux下的diff命令相似。
可以使用该模块比对代码和配置文件的差异,在版本控制方面非常有用。

  • ‘-‘:包含在第一个序列行中,不包含在第二个序列行中
  • ‘+‘:包含在第二个序列行中,不包含在第一个序列行中
  • ‘‘:两个序列行一致
  • ‘?‘:标志两个序列行存在增量差异
  • ‘^‘:标志出两个序列存在的差异字符

字符串比较

import difflib

nginx_config_1 = rC:\Users\longfei\Desktop\nginx1.conf
nginx_config_2 = rC:\Users\longfei\Desktop\nginx2.conf

with open(nginx_config_1 ,encoding=utf-8) as f:
    f1 = f.readlines()

with open(nginx_config_2,encoding=utf-8) as f:
    f2 = f.readlines()

d = difflib.Differ()
diff = d.compare(f1, f2)
print(diff)
# <generator object Differ.compare at 0x000001B948760408>

for line in diff:
    print(line)

结果如下:

技术图片
  user  nginx;
  worker_processes  1;

  error_log  /var/log/nginx/error.log warn;
  pid        /var/run/nginx.pid;

  events {
      worker_connections  1024;
  }

  http {
      include       /etc/nginx/mime.types;
      default_type  application/octet-stream;
      #反向代理的日志配置
      log_format  main  $remote_addr - $remote_user [$time_local] "$request" 
                        $status $body_bytes_sent "$http_referer" 
                        "$http_user_agent" "$http_x_forwarded_for";

      access_log  /var/log/nginx/access.log  main;

      sendfile        on;
      #tcp_nopush     on;

      keepalive_timeout  65;
- 
      #gzip  on;
- 
      include /etc/nginx/conf.d/*.conf;
  
      upstream http-server {
          server 192.168.76.134:80;
-         server 192.168.76.135:80;
?                             ^
+         server 192.168.76.136:80;
?                             ^
                     }
+ 
+     upstream tomcats {
+         server 192.168.0.100:8080 weight=2;  # 2/6次
+         server 192.168.0.101:8080 weight=3;  # 3/6次
+         server 192.168.0.102:8080 weight=1;  # 1/6次
+     }
  
      server {
          listen 80;
          location / {proxy_pass http://http-server; #名称和upstream后的名称一致}
             }
+ 
+     server {
+         listen 8080;
+         location / {proxy_pass http://tomcats;}
+            }
  }
View Code

 

生成HTML文档

采用HtmlDiff()的make_file()方法可以生成HTML文档

import difflib

nginx_config_1 = rC:\Users\longfei\Desktop\nginx1.conf
nginx_config_2 = rC:\Users\longfei\Desktop\nginx2.conf

with open(nginx_config_1 ,encoding=utf-8) as f:
    f1 = f.readlines()

with open(nginx_config_2,encoding=utf-8) as f:
    f2 = f.readlines()

d = difflib.HtmlDiff()
diff = d.make_file(f1,f2)  
#diff生成了一个html页面的代码,将代码保存为html文件中,或者在运行python文件时将结果保存为diff.html(运行python my_diff.py > diff.html),用浏览器打开保存的html文件即可。

技术图片

difflib模块

标签:版本   image   版本控制   gif   users   one   var   form   rem   

原文地址:https://www.cnblogs.com/dxnui119/p/13087329.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!