How can I freeze a dual-mode (GUI and console) application using cx_Freeze?

前端 未结 2 1975
傲寒
傲寒 2020-12-28 23:42

I\'ve developed a Python application that runs both in the GUI mode and the console mode. If any arguments are specified, it runs in a console mode else it runs in the GUI m

相关标签:
2条回答
  • 2020-12-28 23:52

    I found this bit on this page:

    Tip for the console-less version: If you try to print anything, you will get a nasty error window, because stdout and stderr do not exist (and the cx_freeze Win32gui.exe stub will display an error Window). This is a pain when you want your program to be able to run in GUI mode and command-line mode. To safely disable console output, do as follows at the beginning of your program:

    try:
        sys.stdout.write("\n")
        sys.stdout.flush()
    except IOError:
        class dummyStream:
            ''' dummyStream behaves like a stream but does nothing. '''
            def __init__(self): pass
            def write(self,data): pass
            def read(self,data): pass
            def flush(self): pass
            def close(self): pass
        # and now redirect all default streams to this dummyStream:
        sys.stdout = dummyStream()
        sys.stderr = dummyStream()
        sys.stdin = dummyStream()
        sys.__stdout__ = dummyStream()
        sys.__stderr__ = dummyStream()
        sys.__stdin__ = dummyStream()
    

    This way, if the program starts in console-less mode, it will work even if the code contains print statements. And if run in command-line mode, it will print out as usual. (This is basically what I did in webGobbler, too.)

    0 讨论(0)
  • 2020-12-28 23:59

    Raymond Chen has written about this: http://blogs.msdn.com/b/oldnewthing/archive/2009/01/01/9259142.aspx. In short, it's not possible directly under Windows but there are some workarounds.

    I'd suggest shipping two executables - cli and gui one.

    0 讨论(0)
提交回复
热议问题