2015-12-21 44 views
0

目前我得到以下錯誤替代cmp從python 2移動到3?小蟒蛇的經驗。

Traceback (most recent call last): 
File "C:\Users\Dilshad\Desktop\project_7-8-2015\8_bands\Program_camera.py", line 47, in <module> 
if (cmp(before, after) != 0): 
NameError: name 'cmp' is not defined 

當我運行:

# CAMERA IMAGE ANALYZE 
camera_directory = "/Users/Dilshad/Dropbox/Camera Uploads"  # Directory of camera uploads 
os.chdir(camera_directory)            # Change directory to location of photo uploads 
path = "." 
before = dict([(f, None) for f in os.listdir(path)]) 

print('Waiting for image to be uploaded...\n') 
while True:                # Wait a new image in the directory 
    import time 
    time.sleep(2) 
    after = dict([(f, None) for f in os.listdir(path)]) 
    if (cmp(before, after) != 0): 
     break; 
print('New file detected.\n')           # New image detected 

我知道CMP是由蟒蛇3下降,我嘗試了建議(A> B) - (一< b)由通過什麼之後代入(前>)在Python 3的新功能 - (<之後),但我得到以下幾點:

Traceback (most recent call last): 
File "C:\Users\Dilshad\Desktop\project_7-8-2015\8_bands\Program_camera - test.py", line 46, in <module> 
if ((before > after) - (before < after) != 0): 
TypeError: unorderable types: dict() > dict() 

任何想法上我如何完成這個比較?

回答

0

如果您想知道文件是否已添加到(或已從目錄中刪除),請比較dict所具有的keys的數量。
根據你的算法,當找到一個新文件時,應該添加一個新的密鑰(這意味着當刪除一個文件時,你會發現比以前少的密鑰)。

if (len(before.keys()) < len(after.keys())): 
     break; 
print('New file detected.\n')  
0

你可以只是==

a = {'a':1, 'b':2} 
a = {'a':1, 'b':2} 
b = {'a':1, 'b':2} 
print(a == b) 
b['a'] = 3 
print(a == b) 
# reset 
b['a'] = 1 
print(a == b) 
# add a new key-value pair 
b['c'] = 3 
print(a == b) 

它打印

True 
False 
True 
False 
對它們進行比較