简体   繁体   中英

Create windowed exe using py2exe that accepts program arguments

py2exe provides a list of options that can be used to customize how the resulting exe is set up. In particular, it provides the options windows and console , which specify whether the exe should use a console or graphical interface.

I would like my program to hide the console when executed but also accept program arguments.

When I create an exe with the windows option and run the program with valid arguments, the program does not seem to execute.

Here's an example. Let's say my python file is HelloWorld.py :

import sys
import getopt

if __name__ == '__main__':
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'h', ['hello'])
    except getopt.GetoptError:
        sys.exit(2)

    for opt, arg in opts:
        if opt in ('-h', '--hello'):
            print 'Hello world!'

Using the setup setup(console=['HelloWorld.py']) and running the resulting exe with HelloWorld.exe -h outputs Hello world! .

Using the setup setup(windows=['HelloWorld.py']) and running the resulting exe with HelloWorld.exe -h outputs nothing.

You can find an explanation on how py2exe manages stdout and sterr when it packages applications as console application or windows applications at the following link:

http://www.py2exe.org/index.cgi/StderrLog

windows option is for GUI application (wxpython etc) which can catch the stdout and show it in the GUI but without implementing such thing you will need cmd window to print stdout by "print" statement. For example, in wxpython you can start the app with redirect=True option to capture the stdout.

http://www.wxpython.org/docs/api/wx.App-class.html

import wx

if __name__ == '__main__':
    app = wx.App(True)

redirect - Should sys.stdout and sys.stderr be redirected? Defaults to True on Windows and Mac, False otherwise. If filename is None then output will be redirected to a window that pops up as needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM