从 Batch 使用 Pythonw 启动 Python 脚本并赋予它焦点

问题描述

我使用的是 Windows 10,我有一个 PyQt5 应用程序,我使用 .bat 文件启动以使用 venv 解释器。

当我使用 python my_script.py 调用脚本时,它会打开主窗口并在后台显示 Python 控制台。为了摆脱控制台,我尝试使用 pythonw my_script.py 启动它,但随后它在后台打开。

我尝试过 window.setwindowState(Qt.WindowState.WindowActive)window.setFocus() 之类的东西,但这只会使任务栏中的图标闪烁。其他 Google 结果表明 Windows 不再允许程序轻松获取焦点,但话说回来,python 可以在启动时做到这一点,因此我想用 pythonw 复制该行为。>

您可以在下面找到测试代码和批处理文件,上下文正在从自定义 URI 协议启动它。

# https://stackoverflow.com/a/38205984 to register any protocol for testing

import sys
from PyQt5.QtWidgets import QApplication,QMainWindow,QLabel
from PyQt5.QtCore import Qt

class MainWindow(QMainWindow):
    def __init__(self,title):
        super().__init__()

        self.setwindowTitle("Test App")

        label = QLabel(title)
        self.setCentralWidget(label)


if __name__ == '__main__':
    if len(sys.argv) == 1:
        the_title = "I got no arguments"
    else:
        the_title = f"I was run with argument {sys.argv[1]}"
    app = QApplication(sys.argv)

    window = MainWindow(the_title)
    window.show()
    window.setFocus()
    app.exec()

cd %~dp0
call ..\venv\Scripts\activate
start "" "pythonw" "test_url_scheme_one.py" "%1"
deactivate

解决方法

用以下内容替换批处理文件修复它:

start "" "C:\path\to\venv\Scripts\pythonw.exe" "C:\path\to\my_script.py" "%1"

现在窗口在前景和焦点中启动。