'Loop until screen changes
I am trying to automate something in SAP. For that, I enter a transaction code and press enter (done with pywinauto). Now, the screen should change and go to the 'screen2'. However, sometimes due to slow network it takes a lot of time to go to the 'screen2'. If this happens, my next line of code (which is to enter some text in the next screen (again, done with pywinauto keyboard module) does not have the field yet where it should enter the text & hence the script will throw an error. I can give a long time.sleep() but when the network speed is good (which is most of the time), then, giving a long sleep is waste of time and that undermines what i am trying to do, which is to save time.
I have an image which is only available on 'screen2'. So, after i hit enter, i want to search for the image on the screen with the code pyautogui.locateOnScreen(r'CrtDocScreen.png', confidence =0.8) every 0.5 seconds until the image is found. Once the image is found, we know that we are on 'screen2' and we can continue. I am just not able to accomplish this part because when pyautogui.locateOnScreen does not find an image, it throws "ImageNotFoundException" and I do know how-how to take this as a result and continue to loop the image search.
Please help!
Solution 1:[1]
I created the following function that will look for the next screen for 10 seconds and then abort. If the required screen is found within 10 seconds, the loop will break and program will continue.
from datetime import datetime
import pyautogui
from pyscreeze import ImageNotFoundException
def Waitfor (NededScr):
startloop_time = datetime.now()
while True:
try:
pyautogui.locateOnScreen(NededScr, confidence =0.8)
break
except ImageNotFoundException:
time_delta = datetime.now() - startloop_time
if time_delta.total_seconds() >= 10:
print("Could not find the required screen. Document creating for this order aborted")
break
pass
NededScr is the variable with the image, for example: NededScr = r"landingscreen.png"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jaroslav Bezděk |
