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])
比較代碼對象而不是僅僅'co_code'屬性足以識別不同的模塊嗎? –
@JohnGordon:我不知道。它似乎工作,但我真的不知道如何定義代碼對象上的等式比較。你想在這裏完成什麼? – BrenBarn
我正在開發一個作爲編譯好的pyc文件打包在RPM中的軟件應用程序。我試圖想出一種方法來比較兩個這樣的RPM文件來識別兩者之間的任何變化。 –