September 12, 2007
Running a python script on Windows without the console
A common question among new python programmers is, "How do I run my GUI script in Windows without causing a console to appear?"
It's actually quite simple. You can use pythonw.exe instead of python.exe to run it:
You can also change the extension to .pyw instead of .py:
People often want to suppress the console when they're packaging their app for other computers (e.g. via py2exe), and they don't want the users to be distracted by an ugly console. It's also easy to get rid of the console in an app packaged with py2exe; just put the script in the "windows" key of the setup dictionary. Here's an example setup.py that does this.
import py2exe
import sys
import os
import time
VERSION = "1.0"
PROG_NAME = "My Proggy"
DESCRIPTION = "Description of the program"
MANIFEST_TEMPLATE = """
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestversion="1.0">
<assemblyidentity>
</assemblyidentity> version="5.0.0.0"
processorArchitecture="x86"
name="%(name)s"
type="win32"
/>
<description>%(name)s Program</description>
<dependency>
<dependentassembly>
<assemblyidentity>
</assemblyidentity> type="win32"
name="Microsoft.Windows.Common-Controls"
version="6.0.0.0"
processorArchitecture="X86"
publicKeyToken="6595b64144ccf1df"
language="*"
/>
</dependentassembly>
</dependency>
</assembly>
""".strip()
RT_MANIFEST = 24
"""Resource ID in Windows executables"""
def main():
"""Create a setup file"""
manifest = MANIFEST_TEMPLATE % dict(name=PROG_NAME)
ugly_name = PROG_NAME.replace(" ", "")
prog_dict = dict(version=VERSION,
company_name = "My Company",
copyright = "(C) My Company",
author = "My Company",
author_email = "support@mycompany.com",
description=DESCRIPTION,
script="main.py",
#icon_resources = [(1, "./res/%s.ico" % ugly_name)],
other_resources = [(RT_MANIFEST, 1, manifest)],
dest_base= ugly_name,
name= "%s Application v %s" % (PROG_NAME,
VERSION)
)
setup_dict = {}
setup_dict['windows'] = [prog_dict]
setup_dict['console'] = []
excludes = ["pywin", "pywin.debugger", "pywin.debugger.dbgcon",
"pywin.dialogs", "pywin.dialogs.list", "win32com.server",
"email"]
options = dict(optimize=2,
dist_dir=PROG_NAME.replace(" ", ""),
excludes=excludes)
setup_dict['options'] = {"py2exe" : options}
# If run without args, build executables, in quiet mode.
if len(sys.argv) == 1:
sys.argv.append("py2exe")
sys.argv.append("-q")
start_time = time.time()
os.chdir(os.path.dirname(__file__))
print "Creating exe…"
setup(
**setup_dict
)
print "Created exe in", time.time() - start_time, "seconds"
if __name__ == "__main__":
main()
first