保持终端对焦

问题描述 投票:8回答:4

我有一个python脚本,它使用selenium来自动化网页,将焦点从需要用户输入的终端上拉开。

无论如何在python中以编程方式将焦点切换回终端?

如果重要的话,我将在Windows 7的Windows命令提示符下运行我的程序,但跨平台的答案将是最有用的。


Attempts

查看win32 API的pywin32包绑定,我有以下内容:

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: ')

由于Microsoft删除了从另一个应用程序获取焦点的能力,SetFocus导致错误pywintypes.error: (5, 'SetFocus', 'Access is denied.')

FlashWindow似乎什么都不做。

python selenium windows-7 cmd
4个回答
5
投票

这是我提出的似乎有效的方法。

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()

然后找到一个窗口让它活跃起来你可以......

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

这是在python 2.7中,这里也是我发现的一些链接,解释了为什么你必须经历这么多麻烦才能切换活动窗口。

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

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


0
投票

这并没有真正回答你的问题,但简单的解决方案是不要把焦点放在首位:

driver = webdriver.PhantomJS()
# ...

PhantomJS webdriver没有任何UI,因此不会窃取焦点。


0
投票

要获得焦点,请查看对this answer的评论。

跨平台方法可以是将Tkinter用于用户GUI,因为它具有为其窗口获取和设置焦点的方法。


0
投票

如果您不关心清除matplotlib框架中显示的任何图形 - 我认为通常情况下,当人们想要将焦点重新放回控制台以供用户输入时 - 请使用以下内容:

plt.close("all")
© www.soinside.com 2019 - 2024. All rights reserved.