>## 题目:
利用python写出一个可在shell中执行的命令**mydiff**,用于比对两个文件之间的区别,输出可读性较强的html页面源码,可保存到html文件中进行查看。
- 格式: mydiff file1 file2 [> save_file]
----
### 实现:
- 1.利用sys.argv函数获取从命令行输入的参数,用于传递参数
```
if len(sys.argv) !=3: # 如果参数数量不为3个输出命令的使用提示
print('''
usage: {} file1 file2 [>] [file to save]
'''.format(sys.argv[0]))
else: # 当输入参数符合要求进行比对
... ...
```
----
- 2.利用difflib.Htmldiff函数进行比对,并输出可读性较强的html页面源码
```
#sys.argv的后两个参数为需要进行比对的文件名
file1 = sys.argv[1]
file2 = sys.argv[2]
try:
with open(file1)as f1 ,open(file2)as f2: # 打开两个文件
content1= f1.read().splitlines(keepends=True) # 读取其中的文件
content2= f2.read().splitlines(keepends=True)
diff = difflib.HtmlDiff() # 创建工具对象
result =diff.make_file(content1,content2) # 获取文件对比结果
print(result) # 输出结果,可以看到html写的源码
except Exception as e: # 出现异常输出提示
print('Error:'+e)
```
----
- 3.文件开头注明解释器位置和编码格式
```
#!/usr/local/python3/bin/python3.6
#encoding=utf-8
```
#### 完整代码:
```
#!/usr/local/python3/bin/python3.6
#encoding=utf-8
import sys
import difflib
if len(sys.argv) !=3: # 如果参数数量不为3个输出命令的使用提示
print('''
usage: {} file1 file2 [>] [file to save]
'''.format(sys.argv[0]))
else: # 当输入参数符合要求进行比对
file1 = sys.argv[1]
file2 = sys.argv[2]
try:
with open(file1)as f1, open(file2)as f2: # 打开两个文件
content1 = f1.read().splitlines(keepends=True) # 读取其中的文件
content2 = f2.read().splitlines(keepends=True)
diff = difflib.HtmlDiff() # 创建工具对象
result = diff.make_file(content1, content2) # 获取文件对比结果
print(result) # 输出结果,可以看到html写的源码
except Exception as e: # 出现异常输出提示
print('Error:' + e)
```
----
- 4.将py文件拷贝至/usr/local/bin/中(此路径已在环境变量中),并增加执行权限。此时利用tab键补齐可以看到mydiff命令
![](https://s1.51cto.com/images/blog/201901/17/933703d9f790b43d4ef5513f68d329ef.png?x-oss-process=image/watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=)
----
- 5.测试命令,输出了一个html编码
![](https://s1.51cto.com/images/blog/201901/17/760cc7ad4d9641d9114ad54271f00e30.png?x-oss-process=image/watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=)
----
- 6.重定向在桌面生成一个html文件(mydiff /etc/passwd /tmp/paswd > /home/kiosk/Desktop/diff.html)
![](https://s1.51cto.com/images/blog/201901/17/cebd23a9c8edf2e63cb757e1111ee6b4.png?x-oss-process=image/watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=)
----
- 7.利用浏览器打开,可以看到可读性很强的html页面
![](https://s1.51cto.com/images/blog/201901/17/83db5eb9c30bea4f90449183d270fd9e.png?x-oss-process=image/watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=)