I know I can use time.sleep(), but I need something that would affect whole script.It is automatic test homework and aplication buttons are clicked almost instantly. It is a bit anoying because I cant see if everything is working as supposed(still learning).
import pyautogui
import time
from pywinauto.application import Application
app = Application(backend="uia").start(r"C:\Users\User\Desktop\WPF_RentACar_3maj\WPFRentACar\bin\Debug\WPFRentACar.exe")
pyautogui.FAILSAFE = True
#app.LoginWIndow.print_control_identifiers()
dlg =app.LoginWindow
dlg.MaximizeButton.click()
dlg.MinimizeButton.click()
dlg.MaximizeButton.click()
dlg.Restore.click()
try:
dlg.Edit1.type_keys("123")
dlg.Edit2.type_keys("123")
dlg.LoginButton.click()
dlg.Button1.click()
finally:
print("Cant login with wrong credentials!")
time.sleep(2)
dlg.Edit1.type_keys("'^a{BACKSPACE}")
dlg.Edit2.type_keys("'^a{BACKSPACE}")
dlg.LoginButton1.click()
time.sleep(5)
time.sleep() does stop the whole script. Or are you using threading or python 2? Also can you tell us what you are also trying to automate.
Related
I'm using PyAutoGui for automation of adding data to certain fullscreen app. Problem is, when I try to Alt+Tab back to my IDE it constantly brings app back to front and messes up my code by pasting data there. I need a way to either prevent script from working when I press Alt+Tab or when window comes out of focus. How do I do that?
I tried:
Ctrl-C
Ctrl-Pause
import _thread
def input_thread(a_list):
raw_input() # use input() in Python3
a_list.append(True)
def do_stuff():
a_list = []
_thread.start_new_thread(input_thread, (a_list,))
while not a_list:
stuff()
I am trying to automate some GUI stuff in Windows. I open a settings window but when waiting for it to open before continuing, it times out:
from pywinauto import Application
app = Application()
app.start(r"explorer shell:::{05d7b0f4-2121-4eff-bf6b-ed3f69b894d9}")
app.window(title_re=".*Notification Area Icons*").wait("exists", timeout=20)
app = Application(backend="uia").connect(title_re=".*Notification Area Icons*")
main_dlg = app.window(title_re=".*Notification Area Icons*")
main_dlg.print_control_identifiers()
Even with the timeout at 20 seconds, it times out. However, if I replace app.window(title_re=".*Notification Area Icons*").wait("exists", timeout=20) with sleep(5) (and add the appropriate import) it works fine. I know the window title is correct because it will print out the control ids when using sleep. I've tried using "exists" and "visible" for the wait as well. I think the other options are more strict so I'm not sure why the wait is not working.
It's possible there are few explorer.exe processes. You can try process-agnostic way:
from pywinauto import Desktop
window_wrapper = Desktop(backend="uia").window(title_re=".*Notification Area Icons*").wait("exists", timeout=20)
print(window_wrapper.process_id())
# and compare with print(app.process)
I'm trying to do something in a Jupyter notebook that runs a continuous process, but with a pause button to interrupt it. Below is a simplified version of what I've done so far, but it seems Ipython wants to complete the entire run() function before it executes commands it receives from the button. The problem, of course, being that run() will never finish unless interrupted.
Interestingly, the below strategy works just fine in my Tkinter frontend so long as I put a pause(0.0001) at the end of the updateGraph() function. Architecturally, I'd be curious why Tkinter is willing to listen to input events during that pause but Jupyter isn't. But more importantly, is there a way to get Jupyter to listen while running run()?
from ipywidgets import Button
from IPython.display import display
startstop = Button(description='Run')
startstop.click = run
display(startstop)
def run(b=None):
running=True
while running:
#Do stuff and update display
updateGraph()
startstop.click = pause
startstop.description = 'Pause'
def pause(b=None):
running = False
startstop.click = run
startstop.description = 'Run'
I prefer using Keyboard for this purpose. It is a much simpler approach to the same problem...
import keyboard
def run():
running=True
while running:
pass # some code here...
if keyboard.is_pressed('alt'):
break
run()
Press Alt key anytime to stop the execution of the program.
I was making a bot that would basically keep the left mouse button clicked or unclicked based on a toggle. I get it to work but then it started lagging my entire computer so I didn't take it one step further, being scared to burn my PC, how It happened to my phone one year ago. So we are finally here asking you guys for some optimization to my project.
Code:
import keyboard
import win32api, win32con
from pynput.mouse import Button, Controller
mouse = Controller()
play=False
def toggle():
global play
if play==False:
play=True
else:
play=False
keyboard.add_hotkey('home',toggle)
played=False
while True:
if play==True and played==False:
played=True
mouse.press(Button.left)
elif play==False:
mouse.release(Button.left)
played=False
else:
pass
You should put a time.sleep() or something to wait between each loop because your while statement is running again and again without any pauses.
You can slow the while loop by inserting a sleep function in it. To do this, import the module time and call the function time.sleep(ms) in your while loop. It will be less reactive but you can set a sleep time of only a few ms and it will be better because the program will not be running at full speed all the time.
Using Win32GUI and Watsup, I'm writing a bit of Python code to automate a search across a database that is accessed through a program that doesn't come with an interface for it. As such, I can take a string from a list and then input it into the search box and press 'lookup'.
However, when the search returns more than 1000 results, the program throws a warning dialog --which is simply a notification of the number of results--which halts the execution of the Python code. I can't get the code to progress past the line where it presses lookup.
At a guess, this would be because it doesn't expect a window or know how to handle a warning--but I don't either, other than manually accepting it. Below is the relevent sample of code, though it's probably not very enlightening. After "clickButton(LookupButton)", the execution halts.
LookupButtonlocation = elemstring.find("Lookup", AuthNameFieldlocation) - 15
#Use Regex search to find handles
number_regex = re.compile(';(\d+);')
AuthNameEdit = int(number_regex.search(elemstring[AuthNameFieldlocation:]).group(1))
LookupButton = int(number_regex.search(elemstring[LookupButtonlocation:]).group(1))
#Input new Author into Edit Field
setEditText(AuthNameEdit, "John Campbell")
#Click lookup button
clickButton(LookupButton)
I'm not a WATSUP user, but I do something very similar using pywinauto - in my case I'm running a number of automated tests that open various 3rd party programs that, in a similar way, throw up inconvenient warning dialogs. It's a bit difficult to deal with dialogs that you don't know about, however if you do know which dialogs appear, but not when they appear, you can start a thread to just deal with those pop-ups. The following is a simple example from what I'm doing, and uses pywinauto but you could adapt the approach for WATSUP:
import time
import threading
class ClearPopupThread(threading.Thread):
def __init__(self, window_name, button_name, quit_event):
threading.Thread.__init__(self)
self.quit_event = quit_event
self.window_name = window_name
self.button_name = button_name
def run(self):
from pywinauto import application, findwindows
while True:
try:
handles = findwindows.find_windows(title=self.window_name)
except findwindows.WindowNotFoundError:
pass #Just do nothing if the pop-up dialog was not found
else: #The window was found, so click the button
for hwnd in handles:
app = application.Application()
app.Connect(handle=hwnd)
popup = app[self.window_name]
button = getattr(popup, self.button_name)
button.Click()
if self.quit_event.is_set():
break
time.sleep(1) #should help reduce cpu load a little for this thread
Essentially this thread is just an infinite loop that looks for a pop-up window by name, and if it finds it, it clicks on a button to close the window. If you have many pop-up windows you can open one thread per popup (bug that's not overly efficient, though). Because it's an infinite loop, I have the thread looking to see if an event is set, to allow me to stop the thread from my main program. So, in the main program I do something like this:
#Start the thread
quit_event = threading.Event()
mythread = ClearPopupThread('Window Popup Title', 'Yes button', quit_event)
# ...
# My program does it's thing here
# ...
# When my program is done I need to end the thread
quit_event.set()
This is not necessarily the only way to deal with your issue, but is a way that's worked for me. Sorry I can't really help you much with dealing with WATSUP (I always found pywinauto a bit easier to use), but I noticed on the WATSUP homepage (http://www.tizmoi.net/watsup/intro.html), Example 2 does something similar without using threads, i.e., looks for a named window and clicks a specific button on that window.