从 Batch 中使用 Pythonw 启动 Python 脚本并赋予其焦点
Posted
技术标签:
【中文标题】从 Batch 中使用 Pythonw 启动 Python 脚本并赋予其焦点【英文标题】:Launch Python Script with Pythonw from Batch and give it Focus 【发布时间】:2021-09-20 22:57:10 【问题描述】:我在 Windows 10 上,我有一个 PyQt5 应用程序,我使用 .bat 文件启动以使用 venv 解释器。
当我使用python my_script.py
调用脚本时,它会在焦点上打开主窗口,但也会在后台显示 Python 控制台。为了摆脱控制台,我尝试使用pythonw my_script.py
启动它,但随后它会在后台静默打开。
我尝试了window.setWindowState(Qt.WindowState.WindowActive)
或window.setFocus()
之类的方法,但这只会使图标在任务栏中闪烁。其他谷歌结果表明 Windows 不再允许程序轻松获取焦点,但话又说回来,python
可以在启动时做到这一点,所以我想用pythonw
复制这种行为。
您可以在下面找到测试代码和批处理文件,上下文是从自定义 URI 协议启动它。
# https://***.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
【问题讨论】:
【参考方案1】:将批处理文件替换为以下修复它:
start "" "C:\path\to\venv\Scripts\pythonw.exe" "C:\path\to\my_script.py" "%1"
现在窗口开始在前景和焦点中。
【讨论】:
以上是关于从 Batch 中使用 Pythonw 启动 Python 脚本并赋予其焦点的主要内容,如果未能解决你的问题,请参考以下文章
python的文件格式有两种,"*.py"和"*.pyw",它们有啥不同?