How to hide console window in python?

Viewed 203080

I am writing an IRC bot in Python.

I wish to make stand-alone binaries for Linux and Windows of it. And mainly I wish that when the bot initiates, the console window should hide and the user should not be able to see the window.

What can I do for that?

9 Answers

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

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.

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

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()
Related