Keeping the terminal in focus

I have a python script that uses selenium to automate a web page, focusing focus from the terminal where user input is required.

Is there anyway in python to switch focus to the terminal programmatically?

I will run my program on the Windows command line in Windows 7, if that matters, but the answer to the cross platform will be most useful.


Attempts

Looking at the pywin32 package pywin32 for the win32 API, I have the following:

 import win32console import win32gui from selenium import webdriver as wd d = wd.Firefox() win32gui.SetFocus(win32console.GetConsoleWindow()) win32gui.FlashWindow(win32console.GetConsoleWindow(), False) input('Should have focus: ') 

SetFocus raises the pywintypes.error: (5, 'SetFocus', 'Access is denied.') due to Microsoft removing the focus feature from another application.

FlashWindow does nothing.

+6
source share
3 answers

Here is what I came up with that seems to work.

 class WindowManager: def __init__(self): self._handle = None def _window_enum_callback( self, hwnd, wildcard ): if re.match(wildcard, str(win32gui.GetWindowText(hwnd))) != None: self._handle = hwnd #CASE SENSITIVE def find_window_wildcard(self, wildcard): self._handle = None win32gui.EnumWindows(self._window_enum_callback, wildcard) def set_foreground(self): win32gui.ShowWindow(self._handle, win32con.SW_RESTORE) win32gui.SetWindowPos(self._handle,win32con.HWND_NOTOPMOST, 0, 0, 0, 0, win32con.SWP_NOMOVE + win32con.SWP_NOSIZE) win32gui.SetWindowPos(self._handle,win32con.HWND_TOPMOST, 0, 0, 0, 0, win32con.SWP_NOMOVE + win32con.SWP_NOSIZE) win32gui.SetWindowPos(self._handle,win32con.HWND_NOTOPMOST, 0, 0, 0, 0, win32con.SWP_SHOWWINDOW + win32con.SWP_NOMOVE + win32con.SWP_NOSIZE) shell = win32com.client.Dispatch("WScript.Shell") shell.SendKeys('%') win32gui.SetForegroundWindow(self._handle) def find_and_set(self, search): self.find_window_wildcard(search) self.set_foreground() 

Then, to find the window and make it active, you can ...

 w = WindowManager() w.find_and_set(".*cmd.exe*") 

This is in python 2.7, there are also some links that I found to explain why you have to face such difficulties in switching active windows.

win32gui.SetActiveWindow () ERROR: The specified procedure was not found

Windows 7: how to bring a window to the foreground no matter what other window has focus?

+3
source

This does not actually answer your question, but a simple solution is to not divert attention in the first place:

 driver = webdriver.PhantomJS() # ... 

PhantomJS web editor PhantomJS not have any user interface, so it does not steal focus.

0
source

To get focus, check out the comments of this answer .

A cross-platform method may be to use Tkinter for a custom GUI, as it has methods to capture and set focus for its windows.

0
source

Source: https://habr.com/ru/post/988109/


All Articles