在python中,我想使用commands.getoutput('diff a.txt b.txt')來比較兩個文件,如果它們相同,則打印「Success!」。如果他們是相同的,那麼我將如何去寫一個滿足的if語句?Python如何檢查是否返回
0
A
回答
0
result = commands.getoutput('diff a.txt b.txt')
if len(result) == 0:
print 'Success'
1
不使用命令使用的操作系統,這是好多了...
import os
os.system("diff a.txt b.txt" + "> diffOutput")
fDiff = open("diffOutput", 'r')
output = ''.join(fDiff.readlines())
if len(output) == 0:
print "Success!"
else:
print output
fDiff.close()
0
爲什麼使用commands.getoutput
?自python 2.6以來,該模塊已被deprecated。另外,你可以用python比較文件。
file_1_path = 'some/path/to/file1'
file_2_path = 'some/path/to/file2'
file_1 = open(file_1_path)
file_2 = open(file_2_path)
if file_1.read() == file_2.read():
print "Success!"
file_1.close()
file_2.close()
給定兩個路徑到不同的文件,open
他們,那麼,從比較中read
爲字符串荷蘭國際集團他們兩個的結果。
+2
這個實現的一個缺點是它需要將這兩個文件的整體一次裝入內存。 –
3
以下更快 - 它將確定文件在第一個區別上是不相同的,而不是讀取它們的全部並計算diff。它還正確處理文件名稱中有空格或不可打印的字符,並且將繼續commands
模塊被刪除後,與Python的未來版本的工作:
import subprocess
if subprocess.Popen(['cmp', '-s', '--', 'a.txt', 'b.txt']).wait() == 0:
print 'Files are identical'
如果使用diff
是一個人爲的例子和你的真實目標爲確定輸出是否給予,你可以用POPEN也這樣做:
import subprocess
p = subprocess.Popen(['diff', '--', 'a.txt', 'b.txt'],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
(stdout, _) = p.communicate()
if p.returncode != 0:
print 'Process exited with error code %r' % p.returncode
if stdout:
print 'Process emitted some output: \n%s' % stdout
else:
print 'Process emitted no output'
檢查returncode
是在UNIX工具尤爲重要,可能有必要的情況下進行區分,其中NO-輸出意味着成功和失敗發生的地方;只看輸出並不總是讓你做出這樣的區分。
1
您能使用filecmp
嗎?
import filecmp
diff = filecmp.cmp('a.pdf','b.pdf')
if diff:
print('Success!')
相關問題
- 1. 如何檢查它是否返回null?
- 2. 如何檢查是否返回爲空?
- 3. 如何檢查SqlDataSource.SelectCommand是否返回null
- 4. 如何檢查方法是否返回Iqueryable返回anyhting
- 5. 檢查LINQ查詢是否返回行
- 6. 檢查是否返回的值是空
- 7. 如何檢查mysql查詢是否返回任何內容?
- 8. 如何檢查查詢是否返回結果?
- 9. 如何檢查結果是否從MySQL查詢返回
- 10. 如何檢查sql查詢是否返回值?
- 11. 如何檢查查詢是否返回了一些值? (MySQL,Php)
- 12. 如何檢查WMI查詢是否返回0行?
- 13. (PHP + PDO + Sqlite3)如何檢查返回的查詢是否爲空?
- 14. 檢查是否單個()LINQ返回NULL
- 15. 檢查VirtualAlloc是否被VirtualAlloc返回
- 16. 檢查是否NSOpenPanel返回目錄
- 17. 檢查C#php soap是否返回soapFault
- 18. 檢查url是否返回404
- 19. iOS檢查JSON返回是否有鍵
- 20. 檢查函數是否返回
- 21. 如何檢查一個單詞是否是迴文(Python)
- 22. 如何檢查JSON是否返回任何說讓行?
- 23. 如何檢查include()是否返回任何內容?
- 24. Python的檢查文件是否存在(返回false,應返回true)
- 25. Python 3 - 檢查索引是否返回錯誤
- 26. 如何檢查是否在Python
- 27. 如何檢查變量是否在python
- 28. 如何檢查UpdatePanel是否回發?
- 29. 如何檢查比較迴文是否?
- 30. 如何檢查類的方法返回是否等於null?
你讀了多少python書/教程? :D – fabrizioM
diff是一個不好的選擇 - 如果你只想知道文件是否匹配,你可以使用'cmp',這樣既快速又高效。此外,檢查退出狀態比輸入字符串更正確(更快,儘管如此)。 –
'commands'也是一個不好的選擇,在新的Python版本中被棄用; 'subprocess'模塊是規範的。 –