Skip to main content
 首页 » 编程设计

python之wxPython 和 CEF Python 3

2025年05月04日11exmyth

查看 Windows 上 CEF Python 3 中的示例文件。

运行 Python 示例脚本时,它会在 Windows 命令提示符中打开一个调试窗口。

我想知道如何不显示这个?

简单来说:

DEBUG = True -- 没有区别,它只是停止了该窗口内的调试,但该窗口仍然显示。

这是 example.py 文件:

# CEF Python 3 example application. 
 
# Checking whether python architecture and version are valid, otherwise an obfuscated 
# error will be thrown when trying to load cefpython.pyd with a message "DLL load failed". 
import platform 
if platform.architecture()[0] != "32bit": 
    raise Exception("Architecture not supported: %s" % platform.architecture()[0]) 
 
import os, sys 
libcef_dll = os.path.join(os.path.dirname(os.path.abspath(__file__)), 
        'libcef.dll') 
if os.path.exists(libcef_dll): 
    # Import the local module. 
    if 0x02070000 <= sys.hexversion < 0x03000000: 
        import cefpython_py27 as cefpython 
    elif 0x03000000 <= sys.hexversion < 0x04000000: 
        import cefpython_py32 as cefpython 
    else: 
        raise Exception("Unsupported python version: %s" % sys.version) 
else: 
    # Import the package. 
    from cefpython3 import cefpython 
 
import cefwindow 
import win32con 
import win32gui 
import time 
 
DEBUG = True 
 
def GetApplicationPath(file=None): 
    import re, os 
    # If file is None return current directory without trailing slash. 
    if file is None: 
        file = "" 
    # Only when relative path. 
    if not file.startswith("/") and not file.startswith("\\") and ( 
            not re.search(r"^[\w-]+:", file)): 
        if hasattr(sys, "frozen"): 
            path = os.path.dirname(sys.executable) 
        elif "__file__" in globals(): 
            path = os.path.dirname(os.path.realpath(__file__)) 
        else: 
            path = os.getcwd() 
        path = path + os.sep + file 
        path = re.sub(r"[/\\]+", re.escape(os.sep), path) 
        path = re.sub(r"[/\\]+$", "", path) 
        return path 
    return str(file) 
 
def ExceptHook(excType, excValue, traceObject): 
    import traceback, os, time, codecs 
    # This hook does the following: in case of exception write it to 
    # the "error.log" file, display it to the console, shutdown CEF 
    # and exit application immediately by ignoring "finally" (_exit()). 
    errorMsg = "\n".join(traceback.format_exception(excType, excValue, 
            traceObject)) 
    errorFile = GetApplicationPath("error.log") 
    try: 
        appEncoding = cefpython.g_applicationSettings["string_encoding"] 
    except: 
        appEncoding = "utf-8" 
    if type(errorMsg) == bytes: 
        errorMsg = errorMsg.decode(encoding=appEncoding, errors="replace") 
    try: 
        with codecs.open(errorFile, mode="a", encoding=appEncoding) as fp: 
            fp.write("\n[%s] %s\n" % ( 
                    time.strftime("%Y-%m-%d %H:%M:%S"), errorMsg)) 
    except: 
        print("cefpython: WARNING: failed writing to error file: %s" % ( 
                errorFile)) 
    # Convert error message to ascii before printing, otherwise 
    # you may get error like this: 
    # | UnicodeEncodeError: 'charmap' codec can't encode characters 
    errorMsg = errorMsg.encode("ascii", errors="replace") 
    errorMsg = errorMsg.decode("ascii", errors="replace") 
    print("\n"+errorMsg+"\n") 
    cefpython.QuitMessageLoop() 
    cefpython.Shutdown() 
    os._exit(1) 
 
def InitDebugging(): 
    # Whether to print & log debug messages 
    if DEBUG: 
        cefpython.g_debug = True 
        cefpython.g_debugFile = GetApplicationPath("debug.log") 
        cefwindow.g_debug = True 
 
def CefAdvanced(): 
    sys.excepthook = ExceptHook 
    InitDebugging() 
 
    appSettings = dict() 
    appSettings["log_file"] = GetApplicationPath("debug.log") 
    appSettings["log_severity"] = cefpython.LOGSEVERITY_INFO 
    appSettings["release_dcheck_enabled"] = True # Enable only when debugging 
    appSettings["browser_subprocess_path"] = "%s/%s" % ( 
            cefpython.GetModuleDirectory(), "subprocess") 
    cefpython.Initialize(appSettings) 
 
    wndproc = { 
        win32con.WM_CLOSE: CloseWindow, 
        win32con.WM_DESTROY: QuitApplication, 
        win32con.WM_SIZE: cefpython.WindowUtils.OnSize, 
        win32con.WM_SETFOCUS: cefpython.WindowUtils.OnSetFocus, 
        win32con.WM_ERASEBKGND: cefpython.WindowUtils.OnEraseBackground 
    } 
 
    browserSettings = dict() 
    browserSettings["universal_access_from_file_urls_allowed"] = True 
    browserSettings["file_access_from_file_urls_allowed"] = True 
 
    windowHandle = cefwindow.CreateWindow(title="CEF Python 3 example",  
            className="cefpython3_example", width=800, height=600,  
            icon="icon.ico", windowProc=wndproc) 
    windowInfo = cefpython.WindowInfo() 
    windowInfo.SetAsChild(windowHandle) 
    browser = cefpython.CreateBrowserSync(windowInfo, browserSettings, 
            navigateUrl=GetApplicationPath("example.html")) 
    cefpython.MessageLoop() 
    cefpython.Shutdown() 
 
def CloseWindow(windowHandle, message, wparam, lparam): 
    browser = cefpython.GetBrowserByWindowHandle(windowHandle) 
    browser.CloseBrowser() 
    return win32gui.DefWindowProc(windowHandle, message, wparam, lparam) 
 
def QuitApplication(windowHandle, message, wparam, lparam): 
    win32gui.PostQuitMessage(0) 
    return 0 
 
if __name__ == "__main__": 
    CefAdvanced() 

请您参考如下方法:

我没看错,但这实际上是我使用 py2exe 的方式。

在 setup.py 文件中,我必须更改:

setup( 
    console=['wxwindow.py'] 
    ,data_files = get_data_files() 
    ,options={"py2exe":{"dll_excludes":dll_excludes, 'optimize': 2}} 
    ,zipfile = "shared.lib" 
) 
 
setup( 
    window=['wxwindow.py'] 
    ,data_files = get_data_files() 
    ,options={"py2exe":{"dll_excludes":dll_excludes, 'optimize': 2}} 
    ,zipfile = "shared.lib" 
) 

所以:

window=['wxwindow.py']