通过.py脚本执行的.exe文件隐藏控制台窗口

2024-09-24 22:19:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图隐藏从EXE文件弹出的控制台窗口。我正在从我自己的EXE(一个Python脚本冻结通过PyInstaller)运行这个EXE。在

我发现,每当我通过IDLE或PyCharm运行脚本时,我都可以隐藏控制台窗口,一切正常。但是如果我把我的脚本转换成一个EXE(使用pyinstaller --onefile),那么它就不能工作了。在

我尝试了几乎每一个Google都对这个问题的搜索做出了回应,但是我仍然不知道如果我把我的脚本转换成一个EXE文件并运行它,我怎么能隐藏控制台窗口。在

我最后一次尝试:

import subprocess
import win32gui
import time

proc = subprocess.Popen(["MyExe.exe"])
# lets wait a bit to app to start
time.sleep(3)

def enumWindowFunc(hwnd, windowList):
    """ win32gui.EnumWindows() callback """
    text = win32gui.GetWindowText(hwnd)
    className = win32gui.GetClassName(hwnd)
    #print hwnd, text, className
    if text.find("MyExe.exe") >= 0:
        windowList.append((hwnd, text, className))

myWindows = []
# enumerate thru all top windows and get windows which are ours
win32gui.EnumWindows(enumWindowFunc, myWindows)

# now hide my windows, we can actually check process info from GetWindowThreadProcessId
# http://msdn.microsoft.com/en-us/library/ms633522(VS.85).aspx
for hwnd, text, className in myWindows:
    win32gui.ShowWindow(hwnd, False)

# as our notepad is now hidden
# you will have to kill notepad in taskmanager to get past next line
proc.wait()

Tags: 文件totextimport脚本timewindowsproc
2条回答

可以在Pyinstaller中使用-w选项。在

例如

pyinstaller -F -w FILENAME

你可以通过英明学到更多

pyinstaller -h

我希望这能帮助你。在

横向考虑,一个解决方案可能是从Windows的任务调度器application*运行应用程序,并将任务设置为Run whether user is logged on or not。在

Run whether user is logged on or not设置使应用程序以不可见的方式运行,这意味着屏幕上不会显示任何窗口、任务栏图标或控制台窗口。在

*任务调度器默认安装在Windows中。把它的名字输入Cortana运行

相关问题 更多 >