如何在 Python 中隐藏控制台窗口?

我正在用 Python 编写一个 IRC 机器人。

我希望为 Linux 和 Windows 制作独立的二进制文件。主要我希望,当机器人启动时,控制台窗口应该隐藏,用户不应该能够看到窗口。

我能做什么?

209685 次浏览

In linux, just run it, no problem. In Windows, you want to use the pythonw executable.

Update

Okay, if I understand the question in the comments, you're asking how to make the command window in which you've started the bot from the command line go away afterwards?

  • UNIX (Linux)

$ nohup mypythonprog &

  • Windows

C:/> start pythonw mypythonprog

I think that's right. In any case, now you can close the terminal.

Simply save it with a .pyw extension. This will prevent the console window from opening.

On Windows systems, there is no notion of an “executable mode”. The Python installer automatically associates .py files with python.exe so that a double-click on a Python file will run it as a script. The extension can also be .pyw, in that case, the console window that normally appears is suppressed.

Explanation at the bottom of section 2.2.2

On Unix Systems (including GNU/Linux, macOS, and BSD)

Use nohup mypythonprog &, and you can close the terminal window without disrupting the process. You can also run exit if you are running in the cloud and don't want to leave a hanging shell process.

On Windows Systems

Save the program with a .pyw extension and now it will open with pythonw.exe. No shell window.

For example, if you have foo.py, you need to rename it to foo.pyw.

If all you want to do is run your Python Script on a windows computer that has the Python Interpreter installed, converting the extension of your saved script from '.py' to '.pyw' should do the trick.

But if you're using py2exe to convert your script into a standalone application that would run on any windows machine, you will need to make the following changes to your 'setup.py' file.

The following example is of a simple python-GUI made using Tkinter:

from distutils.core import setup
import py2exe
setup (console = ['tkinter_example.pyw'],
options = { 'py2exe' : {'packages':['Tkinter']}})

Change "console" in the code above to "windows"..

from distutils.core import setup
import py2exe
setup (windows = ['tkinter_example.pyw'],
options = { 'py2exe' : {'packages':['Tkinter']}})

This will only open the Tkinter generated GUI and no console window.

This will hide your console. Implement these lines in your code first to start hiding your console at first.

import win32gui, win32con


the_program_to_hide = win32gui.GetForegroundWindow()
win32gui.ShowWindow(the_program_to_hide , win32con.SW_HIDE)

Update May 2020 :

If you've got trouble on pip install win32con on Command Prompt, you can simply pip install pywin32.Then on your python script, execute import win32.lib.win32con as win32con instead of import win32con.

To show back your program again win32con.SW_SHOW works fine:

win32gui.ShowWindow(the_program_to_hide , win32con.SW_SHOW)

Some additional info. for situations that'll need the win32gui solution posted by Mohsen Haddadi earlier in this thread:

As of python 361, win32gui & win32con are not part of the python std library. To use them, pywin32 package will need to be installed; now possible via pip.

More background info on pywin32 package is at: How to use the win32gui module with Python?.

Also, to apply discretion while closing a window so as to not inadvertently close any window in the foreground, the resolution could be extended along the lines of the following:

try     :


import win32gui, win32con;


frgrnd_wndw = win32gui.GetForegroundWindow();
wndw_title  = win32gui.GetWindowText(frgrnd_wndw);
if wndw_title.endswith("python.exe"):
win32gui.ShowWindow(frgrnd_wndw, win32con.SW_HIDE);
#endif
except  :
pass

a decorator factory for this (windows version, unix version should be easier via os.fork)

def deco_factory_daemon_subprocess(*, flag_env_var_name='__this_daemon_subprocess__', **kwargs_for_subprocess):
def deco(target):
@functools.wraps(target)
def tgt(*args, **kwargs):
if os.environ.get(flag_env_var_name) == __file__:
target(*args, **kwargs)
else:
os.environ[flag_env_var_name] = __file__
real_argv = psutil.Process(os.getpid()).cmdline()
exec_dir, exec_basename = path_split(real_argv[0])
if exec_basename.lower() == 'python.exe':
real_argv[0] = shutil.which('pythonw.exe')
kwargs = dict(env=os.environ, stdout=subprocess.PIPE, stderr=subprocess.PIPE, )
kwargs.update(kwargs_for_subprocess)
subprocess.Popen(real_argv, **kwargs)


return tgt


return deco

use it like this:

@deco_factory_daemon_subprocess()
def run():
...




def main():
run()

After writing the code you want to convert the file from .py to .exe, so possibly you will use pyinstaller and it is good to make exe file. So you can hide the console in this way:

pyinstaller --onefile main.py --windowed

I used to this way and it works.

just change the file extension from .py to .pyw

As another answer for all upcoming readers:

If you are using Visual Studio as IDE, you can set "Window Application" in the Project settings with a single checkmark. Which is working with py-extension as well.