2012-05-04 63 views
0

在python中,我想使用commands.getoutput('diff a.txt b.txt')來比較兩個文件,如果它們相同,則打印「Success!」。如果他們是相同的,那麼我將如何去寫一個滿足的if語句?Python如何檢查是否返回

+2

你讀了多少python書/教程? :D – fabrizioM

+2

diff是一個不好的選擇 - 如果你只想知道文件是否匹配,你可以使用'cmp',這樣既快速又高效。此外,檢查退出狀態比輸入字符串更正確(更快,儘管如此)。 –

+1

'commands'也是一個不好的選擇,在新的Python版本中被棄用; 'subprocess'模塊是規範的。 –

回答

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 – TJD

+1

@TJD我認爲提出替代解決方案是合理的,考慮到'commands'模塊從2.6開始已被棄用,並且沒有理由給出'commands'爲什麼是必需的。 – Wilduck

+0

@Wilduck,我確定我同意備用解決方案。但是,這個特定問題的癥結在於'我如何處理運行命令並檢測到沒有任何東西被髮送到標準輸出' – TJD

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!')