7

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 mode.

I've managed to freeze this using cx_Freeze. I had some problems hiding the black console window that would pop up with wxPython and so I modified my setup.py script like this:

import sys

from cx_Freeze import setup, Executable

base = None
if sys.platform == "win32":
    base = "Win32GUI"

setup(
        name = "simple_PyQt4",
        version = "0.1",
        description = "Sample cx_Freeze PyQt4 script",
        executables = [Executable("PyQt4app.py", base = base)])

This works fine but now when I try to open up my console and run the executable from there, it doesn't output anything. I don't get any errors or messages so it seems that cx_Feeze is redirecting the stdout somewhere else.

Is is possible to get it to work with both mode? Nothing similar to this seems to be documented anywhere. :(

Thanks in advance.

Mridang

Mridang Agarwalla
  • 43,201
  • 71
  • 221
  • 382

2 Answers2

14

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.)

Mridang Agarwalla
  • 43,201
  • 71
  • 221
  • 382
  • I've put this snippet in my code, but I'm still getting an error. This might have something to do with using colorama in my code, a library which outputs coloured text. Do you know how to fix this, too? I've added [a screenshot](http://i.imgur.com/1zVKo0c.png) to clarify the error. Hope you can help me. – Exeleration-G May 15 '13 at 20:50
2

Raymond Chen has written about this. In short, it's not possible directly under Windows but there are some workarounds.

I'd suggest shipping two executables - a CLI and GUI one.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Zart
  • 1,421
  • 10
  • 18