问题
I wrote a GUI automation script in python that opens a web browser, does some tests in the browser and then closes the browser. It does so in a loop going up through hundreds of thousands of iterations.
I've run into problems where the program would hang and I would get no browser instances open or sometimes up to 20 instances open. I would like to create an error check to make sure there is only one browser instance open at a time (kill the browser completely and restart the iteration if there are many instances open and/or make sure a browser instance is open before going through an iteration of the loop).
The PID for the browser obviously changes through every iteration of the loop and as far as I know, there is no way to assign PIDs. Another solution I thought of is making a system call to the terminal and somehow utilizing the tasklist and taskkill commands but have still not figured out a way to do what I want.
Any suggestions would be greatly appreciated!
Update:
I understand I can search windows processes by name but how would I put that into a boolean expression like
if tasklist contains firefox.exe
taskkill firefox.exe
else
open firefox
Second Update:
I have the following that I was able to code in Ruby which works:
if system('tasklist | find "firefox.exe"') == true
a = 1
elsif system('tasklist | find "firefox.exe"') == false
a = 0
end
How would I accomplish this in Python?
Answer I was looking for:
b = (str(os.system('tasklist | find "firefox.exe"')))
if b == '1':
b = 'false'
elif b == '0':
b = 'true'
print b
回答1:
Ive been doing similar things
i think you may want pywinauto
from pywinauto.findwindows import find_windows
find_windows(best_match='YOURWINDOWNAMEHERE')
this will raise an exception if YOURWINDOWNAMEHERE is not open
edit: actually for firefox or chrome, it only works if "YOURWINDOWNAMEHERE" is whatever the page you are on is for example this page is "python - How do i programmatically ..."
if it finds it, it will return an int, as far as i know this int is supposed to be able to reference to the window.
example:.
>>>find_windows(best_match="calculator") #this gets an exception
# ::I manually open Calculator now ::
>>>find_windows(best_match="calculator")
[12345] #orwhatever process number it gets
回答2:
I used taskill to kill the Android logger (logcat) using the window title from Java like this:
taskkill /F /FI "WINDOWTITLE eq logcat"
and the emulator using the file name:
taskkill /F /IM emulator-arm.exe
Should work in your case.
来源:https://stackoverflow.com/questions/16428588/how-do-i-programmatically-check-for-open-browser-instances-on-a-windows-machine