Python - 如何在脚本运行时隐藏命令提示符窗口?

3 投票
2 回答
7051 浏览
提问于 2025-04-18 13:40

我该如何在运行我的Python脚本时,去掉桌面上这个黑色的命令提示符窗口?

我使用Python 2 exe把service.py脚本转换成了exe文件,一切都运行得很好,但当这个.exe文件在运行时,我不想显示这个固定的命令提示符窗口。

在这里输入图片描述

service.py:

#!/usr/bin/env python
import os
import ctypes
from subprocess import Popen, PIPE

def Mbox(title, text, style):
  ctypes.windll.user32.MessageBoxA(0, text, title, style)

python_check = os.path.exists("C:/Python27/python.exe")
g_check = os.path.exists("C:/dev_appserver.py")

if python_check & g_check:
  p0 = Popen(['C:/Python27/python.exe', 'C:/dev_appserver.py', '--host', '0.0.0.0', '--port', '8080', 'C:/application'], stdout=PIPE, stdin=PIPE, stderr=PIPE, shell=True)
  out, err = p0.communicate("n\n")

else:
  Mbox('Notice', 'Launching service failed please make sure C:\Python27\python.exe and C:/dev_appserver.py', 0)

setup.py:

from distutils.core import setup
import py2exe
setup(console=['service.py'])

2 个回答

5

我刚刚在这里看到这个内容:
https://github.com/PySimpleGUI/PySimpleGUI/issues/200#issuecomment-732483328

你可以安装这个库: pip install pywin32
然后,你可以在项目的最上面添加这些代码:

import win32gui, win32con

hide = win32gui.GetForegroundWindow()
win32gui.ShowWindow(hide, win32con.SW_HIDE)
1

在setup.py文件中,你必须把console改成windows

像这样:

windows=["service.py"],
    options={"py2exe":
       {"optimize": 2,
          "bundle_files": 0,
          "ascii": 0}}

撰写回答