學習筆記,有錯必糾
管道
大部分操作系統都提供了命令行接口,也稱爲字符界面shell,字符界面通常會提供命令來瀏覽文件系統和啓動應用程序,例如,在windows中,可以使用cd來更換目錄,敲入python來啓動python。任何在字符界而能啓動的程序,都可以在python中使用管道對象來啓動。
python實現
我們可以利用os.popen
來顯示當前工作目錄下的內容,並使用read
一次讀取所有輸出:
import os
cmd1 = 'dir'
fp = os.popen(cmd1)
res = fp.read()
print(res)
部分輸出:
2020/05/17 09:57 <DIR> .
2020/05/17 09:57 <DIR> ..
2020/05/17 09:57 330 dbm_study.py
2020/05/17 09:57 3,113 find_duplicates.py
2020/05/15 12:37 603 koch.py
2020/05/15 11:25 260 mypolygon.py
2020/05/15 15:18 349 my_factorial.py
2020/05/15 16:21 356 NewtonMethod.py
2020/05/16 22:33 109 os_study.py
2020/05/16 23:39 221 pickle_study.py
2020/05/17 09:57 100 popen_study.py
2020/05/16 12:45 529 ReverseLookup.py
2020/05/16 23:14 43 testdatabase.bak
2020/05/16 23:14 526 testdatabase.dat
2020/05/17 09:05 43 testdatabase.dir
2020/05/16 22:05 395 tuple01.py
14 個文件 6,977 字節
2 個目錄 14,654,345,216 可用字節
我們也可以計算文件的MD5碼:
import os
cmd2 = 'certutil -hashfile os_study.py MD5'
fp = os.popen(cmd2)
res = fp.read()
print(res)
輸出:
MD5 哈希(文件 os_study.py):
ea 77 14 85 38 af 8b 56 91 6b dd 06 36 a5 9e 89
CertUtil: -hashfile 命令成功完成。
MD5值簡介
MD5的全稱是Message-Digest Algorithm 5,它一種被廣泛使用的密碼散列函數,可以產生出一個128位(16字節)的散列值(hash value),用於來確保信息傳輸完整一致。
MD5值等同於文件的ID,它的值是唯一的。 如果文件已被修改(例如嵌入式病毒,特洛伊木馬等),其MD5值將發生變化。 因此,一些常規下載URL提供文件MD並且通常提供MD5值。 如果用戶在下載後發現他們的MD5值與網站公告不一致,可能是文件被修改過或者下載出錯。
當然,我們也可使用readline一行一行的讀取:
import os
cmd2 = 'certutil -hashfile os_study.py MD5'
fp = os.popen(cmd2)
count = 0
while True:
count += 1
res = fp.readline()
if res:
print('第{}行:'.format(count), res)
else:
break
輸出:
第1行: MD5 哈希(文件 os_study.py):
第2行: ea 77 14 85 38 af 8b 56 91 6b dd 06 36 a5 9e 89
第3行: CertUtil: -hashfile 命令成功完成。
最後,當我們完成操作時,需要關閉這個管道:
fp.close()
比較兩個文件內容是否相同
我們可以通過生成文件的MD5值,來對比兩個文件是否包含相同的內容,不同的內容生成相同MD5值的概率極低,所以我們可以放心使用。
我有三個txt文件,它們分別是test1.txt,test2.txt,test1_copy.txt
test1.txt和test1_copy.txt內容相同,和test2.txt內容不同.
現在,我們用MD5驗證一下:
# -*- coding: utf-8 -*-
import os
cmd1 = 'certutil -hashfile test1.txt MD5'
fp1 = os.popen(cmd1)
test1_md5 = fp1.read().split('\n')[1]
filenames = ['test2.txt', 'test1_copy.txt']
for item in filenames:
cmd2 = 'certutil -hashfile {} MD5'.format(item)
fp2 = os.popen(cmd2)
item_md5 = fp2.read().split('\n')[1]
if test1_md5 == item_md5:
print('{}和test1.txt內容相同'.format(item))
else:
print('{}和test1.txt內容不同'.format(item))
fp1.close()
fp2.close()
輸出:
test2.txt和test1.txt內容不同
test1_copy.txt和test1.txt內容相同