我开发了一个 Python 应用程序,它可以在 GUI 模式和控制台模式下运行。如果指定了任何参数,它将以控制台模式运行,否则以 GUI 模式运行。
我已经设法使用 cx_Freeze 卡住了它。我在隐藏 wxPython 弹出的黑色控制台窗口时遇到了一些问题,所以我修改了我的 setup.py
脚本,如下所示:
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)])
这工作正常,但现在当我尝试打开我的控制台并从那里运行可执行文件时,它没有输出任何内容。我没有收到任何错误或消息,因此 cx_Feeze 似乎正在将标准输出重定向到其他地方。
有没有可能让它在两种模式下都工作?任何地方似乎都没有类似的记录。 :(
提前致谢。
马里当
最佳答案
我在 this 上找到了这个位页:
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.)
关于python - 如何使用 cx_Freeze 卡住双模式(GUI 和控制台)应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2883205/