2015-10-20 110 views
0

爲什麼下面兩個Python代碼模塊在編譯爲pyc格式時具有相同的co_code屬性?不同的python模塊給出相同的co_code對象

模塊1:

def foo(): 
    response = 'success' 

    success = 'success' in response 

    if not success: 
     raise Exception('failure: %s' % response) 

模塊2:

def foo(): 
    response = 'success' 

    success = 'success' in response 

    if not success: 
     if 'failure: ' in response: 
      reason = response[len('failure: '):] 
      raise Exception('failure: %s' % reason) 

     else: 
      raise Exception('neither success nor failure found in response') 

如果唯一的區別是,比方說,在字符串中,我可以看到爲什麼co_code屬性是相同的。但是這兩個模塊似乎有很大的不同。

這裏是我用來執行比較的代碼:

import marshal 
import sys 

def get_pyc_code(path): 
    '''Extract code object from compiled .pyc file.''' 

    try: 
     handle = open(path, 'rb') 

    except IOError as ex: 
     print str(ex) 
     sys.exit() 

    magic = handle.read(4) 
    moddate = handle.read(4) 

    code = marshal.load(handle) 
    handle.close() 
    return code 

def compare_codes(path1, path2): 
    ''' 
    Compare the full code objects and co_code attributes of pyc files 
    path1 and path2. 
    ''' 

    code1 = get_pyc_code(path1) 
    code2 = get_pyc_code(path2) 

    code_same_full = (code1 == code2) 
    code_same_attr = (code1.co_code == code2.co_code) 

    if code_same_full and code_same_attr: 
     print 'pyc files are identical' 

    else: 
     print('full code objects the same: %s' % code_same_full) 
     print('co_code attributes the same: %s' % code_same_attr) 

if __name__ == '__main__': 
    if len(sys.argv) == 3: 
     compare_codes(sys.argv[1], sys.argv[2]) 

    else: 
     print('usage: %s foo.pyc bar.pyc' % sys.argv[0]) 

回答

1

模塊級代碼對象的代碼本身並不代表它裏面的函數的代碼。你可以看到的代碼是什麼,如果你使用dis(我用c1這裏的代碼對象):

>>> dis.dis(c1) 
    1   0 LOAD_CONST    0 (<code object foo at 000000000234D230, file "m1", line 1>) 
       3 MAKE_FUNCTION   0 
       6 STORE_NAME    0 (foo) 
       9 LOAD_CONST    1 (None) 
      12 RETURN_VALUE 

你可以看到,該模塊的代碼上是相同的,因爲這兩個模塊做什麼,但定義單一功能。 函數的代碼是不同的,但這不是你在這裏看到的。

+0

比較代碼對象而不是僅僅'co_code'屬性足以識別不同的模塊嗎? –

+0

@JohnGordon:我不知道。它似乎工作,但我真的不知道如何定義代碼對象上的等式比較。你想在這裏完成什麼? – BrenBarn

+0

我正在開發一個作爲編譯好的pyc文件打包在RPM中的軟件應用程序。我試圖想出一種方法來比較兩個這樣的RPM文件來識別兩者之間的任何變化。 –

相關問題