2016-06-07 56 views
0

我回顧了其他問題,例如(Python 'if x is None' not catching NoneType),我沒有發現這些信息可用於我的場景。Python3「如果」沒有捕捉到它正在檢查的內容

import pyautogui 

########################## 
#This is a looping routine to search for the current image and return its coordinates 
########################## 

def finder(passedImage, workSpace): #start the finder func 
    print (passedImage) #print the image to be found 
    currentImage = pyautogui.locateOnScreen(passedImage,region=(workSpace), grayscale=True) #search for the image on the screen 
    if currentImage == None: # if that initial search goes "none" ... 
     print ("Looking") #Let us know we are looking 
     finder(passedImage,workSpace) #go and do the function again 
    print(currentImage) #print out the coordinates 
    currentImageX, currentImageY = pyautogui.center(currentImage) #get the X and Y coord 
    pyautogui.click(currentImageX, currentImageY) #use the X and Y coords for where to click 
    print(currentImageX, currentImageY) #print the X and Y coords 

這個想法對於腳本來說很簡單。這只是找到一個圖像的座標,然後點擊它使用pyautogui庫(模塊?我的新術語)

它的所有工作保存爲「if currentImage == None:」位。

當currentImage爲None時會捕獲一些次,然後適當地重新運行該函數以獲取它,但有時它不會。我似乎無法在工作中發現任何背後的原因或其他原因,也無法找到任何原因。

如何,我可以檢查None,然後在那裏是沒有將是巨大的迴應任何建議:)

一個例子錯誤是拋出如下:

Traceback (most recent call last): 
File "fsr_main_001.py", line 57, in <module> 
newItem() 
File "fsr_main_001.py", line 14, in newItem 
finder.finder(passedImage,workSpace) 
File "/home/tvorac/python/formAutomation/finder.py", line 14, in finder 
currentImageX, currentImageY = pyautogui.center(currentImage) #get the X and Y coord 
File "/usr/local/lib/python3.5/dist-packages/pyscreeze/__init__.py", line 398, in center 
return (coords[0] + int(coords[2]/2), coords[1] + int(coords[3]/2)) 
TypeError: 'NoneType' object is not subscriptable 
+0

再次調用遞歸取景不會改變的事實,currentImage是無時,遞歸的回報。 –

回答

1

我覺得發生了什麼當你說你正在重新運行這個函數的時候,你是這樣遞歸的。有沒有return後,新的呼叫finder

if currentImage == None: # if that initial search goes "none" ... 
    print ("Looking") #Let us know we are looking 
    finder(passedImage,workSpace) #go and do the function again 
print(currentImage) #print out the coordinates 

一旦finder()呼叫已完成了它的東西,控制返回到函數,其中currentImageNone的實例,並將其與打印進行,pyautogui.center等上。

鑑於這可能會導致一些相當深的遞歸,它可能不是尋找圖像的最佳方法。相反,某種循環是最好的。

currentImage = None 
while currentImage is None: 
    currentImage = pyautogui.locateOnScreen(passedImage,region=(workSpace), grayscale=True) #search for the image on the screen 

(或類似的東西,添加了超時,最大重試次數,等等)