Python3 Если не улавливает то, что проверяет

Я просмотрел другие вопросы, такие как ( Python 'if x is None' не перехватывает NoneType ), и я не обнаружил, что эта информация пригодна для моего сценария.

    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, а затем ответить на то, что 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

person Todd Lewden    schedule 07.06.2016    source источник
comment
Повторный рекурсивный вызов средства поиска не изменит того факта, что currentImage имеет значение None при возврате рекурсии.   -  person Daniel Roseman    schedule 07.06.2016


Ответы (1)


Я думаю, что происходит то, что когда вы говорите, что повторно запускаете функцию, вы делаете это рекурсивно. После нового вызова finder нет return:

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() сделал свое дело, управление возвращается к экземпляру функции, где currentImage было None, и продолжается печать, pyautogui.center и так далее.

Учитывая, что это может привести к довольно глубокой рекурсии, это, вероятно, не лучший подход к поиску изображения. Вместо этого лучше всего подойдет какая-нибудь петля.

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

(или что-то подобное, с добавленными тайм-аутами, максимальным количеством повторных попыток и т.д.)

person Simon Fraser    schedule 07.06.2016