def OnClose(self, event): # Remove all CEF browser references so that browser is closed # cleanly. Otherwise there may be issues for example with cookies # not being flushed to disk when closing app immediately # (Issue 158). del self.javascriptExternal.mainBrowser del self.clientHandler.mainBrowser del self.browser # Destroy wx frame, this will complete the destruction of CEF browser self.Destroy() # In wx.chromectrl calling browser.CloseBrowser and/or self.Destroy # may cause crashes when embedding multiple browsers in tab # (Issue 107). In such case instead of calling CloseBrowser/Destroy # try this code: # | self.browser.ParentWindowWillClose() # | event.Skip() global g_countWindows g_countWindows -= 1 if g_countWindows == 0: # On Win/Linux the call to cefpython.Shutdown() is after # app.MainLoop() returns, but on Mac it needs to be here. cefpython.Shutdown() print("[wxpython.py] OnClose: Exiting") wx.GetApp().Exit()
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" (os._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 exceptionHook(exceptionType, exceptionValue, traceObject): errorMessage = os.linesep.join(traceback.format_exception(exceptionType, exceptionValue, traceObject)) errorFile = getApplicationPath("error.log") try: applicationEncoding = cefpython.g_applicationSettings["string_encoding"] except: applicationEncoding = "utf-8" if type(errorMessage) == bytes: errorMessage = errorMessage.decode(encoding=applicationEncoding, errors="replace") try: with codecs.open(errorFile, mode='a', encoding=applicationEncoding) as fp: fp.write((os.linesep + '[%s] %s' + os.linesep) % (time.strftime("%d-%m-%Y %H:%M:%S"), errorMessage)) except: print("cloudburst: WARNING: failed writing to error file: %s" % errorFile) # Convert error message to ascii before printing to prevent errors like this: # UnicodeEncodeError: 'charmap' codec can't encode characters errorMessage = errorMessage.encode('ascii', errors='replace') errorMessage = errorMessage.decode('ascii', errors='replace') print os.linesep + errorMessage + os.linesep cefpython.QuitMessageLoop() cefpython.Shutdown() os._exit(1)
def run(self): logging.info("PySide2 version: %s" % PySide2.__version__) logging.info("QtCore version: %s" % QtCore.__version__) sys.excepthook = ExceptHook settings = {} settings["log_file"] = GetApplicationPath("debug.log") settings["log_severity"] = cefpython.LOGSEVERITY_INFO settings["release_dcheck_enabled"] = True # Enable only when debugging settings["browser_subprocess_path"] = "%s/%s" % ( cefpython.GetModuleDirectory(), "subprocess") cefpython.Initialize(settings) app = CefApplication(sys.argv) mainWindow = MainWindow(self.url) mainWindow.show() app.exec_() app.stopTimer() # Need to destroy QApplication(), otherwise Shutdown() fails. # Unset main window also just to be safe. del mainWindow del app cefpython.Shutdown()
def CefAdvanced(): sys.excepthook = ExceptHook InitDebugging() appSettings = dict() appSettings["log_file"] = GetApplicationPath("debug.log") # LOGSEVERITY_INFO - less debug oput. # LOGSEVERITY_DISABLE - will not create "debug.log" file. appSettings["log_severity"] = cefpython.LOGSEVERITY_VERBOSE # Enable only when debugging, otherwise performance might hurt. appSettings["release_dcheck_enabled"] = True # Must be set so that OnUncaughtException() is called. appSettings["uncaught_exception_stack_size"] = 100 cefpython.Initialize(applicationSettings=appSettings) # Closing main window quits the application as we define # WM_DESTOROY message. 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 } windowHandle = cefwindow.CreateWindow( title="CefAdvanced", className="cefadvanced", width=900, height=710, icon="icon.ico", windowProc=wndproc) browserSettings = dict() browserSettings["history_disabled"] = False browserSettings["universal_access_from_file_urls_allowed"] = True browserSettings["file_access_from_file_urls_allowed"] = True javascriptBindings = cefpython.JavascriptBindings( bindToFrames=False, bindToPopups=True) windowInfo = cefpython.WindowInfo() windowInfo.SetAsChild(windowHandle) browser = cefpython.CreateBrowserSync( windowInfo, browserSettings=browserSettings, navigateUrl=GetApplicationPath("cefadvanced.html")) browser.SetUserData("outerWindowHandle", windowInfo.parentWindowHandle) browser.SetClientHandler(ClientHandler()) browser.SetJavascriptBindings(javascriptBindings) javascriptRebindings = JavascriptRebindings(javascriptBindings, browser) javascriptRebindings.Bind() browser.SetUserData("javascriptRebindings", javascriptRebindings) cefpython.MessageLoop() cefpython.Shutdown()
def ExceptHook(type, value, traceObject): import traceback, os, time # This hook does the following: in case of exception display it, # write to error.log, shutdown CEF and exit application. error = "\n".join(traceback.format_exception(type, value, traceObject)) with open(GetApplicationPath("error.log"), "a") as file: file.write("\n[%s] %s\n" % (time.strftime("%Y-%m-%d %H:%M:%S"), error)) print("\n" + error + "\n") cefpython.QuitMessageLoop() cefpython.Shutdown() # So that "finally" does not execute. os._exit(1)
def CefAdvanced(): sys.excepthook = ExceptHook appSettings = dict() # appSettings["cache_path"] = "webcache/" # Disk cache if DEBUG: # cefpython debug messages in console and in log_file appSettings["debug"] = True cefwindow.g_debug = True 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 if os.path.exists("icon.ico"): icon = os.path.abspath("icon.ico") else: icon = "" windowHandle = cefwindow.CreateWindow(title="pywin32 example", className="cefpython3_example", width=1024, height=768, icon=icon, windowProc=wndproc) windowInfo = cefpython.WindowInfo() windowInfo.SetAsChild(windowHandle) browser = cefpython.CreateBrowserSync( windowInfo, browserSettings, navigateUrl=GetApplicationPath("example.html")) cefpython.MessageLoop() cefpython.Shutdown()
def CefSimple(): sys.excepthook = ExceptHook cefpython.g_debug = True cefpython.Initialize() 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 } windowHandle = cefwindow.CreateWindow( title="CefSimple", className="cefsimple", width=800, height=600, icon="icon.ico", windowProc=wndproc) windowInfo = cefpython.WindowInfo() windowInfo.SetAsChild(windowHandle) browser = cefpython.CreateBrowserSync( windowInfo, browserSettings={}, navigateUrl=GetApplicationPath("cefsimple.html")) cefpython.MessageLoop() cefpython.Shutdown()
# not be called anymore. if not USE_EVT_IDLE: self.timer.Stop() if __name__ == '__main__': sys.excepthook = ExceptHook settings = { "debug": False, # cefpython debug messages in console and in log_file "log_severity": cefpython.LOGSEVERITY_INFO, # LOGSEVERITY_VERBOSE "log_file": GetApplicationPath("debug.log"), # Set to "" to disable. # This directories must be set on Linux "locales_dir_path": cefpython.GetModuleDirectory() + "/locales", "resources_dir_path": cefpython.GetModuleDirectory(), "browser_subprocess_path": "%s/%s" % (cefpython.GetModuleDirectory(), "subprocess") } # print("browser_subprocess_path="+settings["browser_subprocess_path"]) cefpython.Initialize(settings) print('wx.version=%s' % wx.version()) app = MyApp(False) app.MainLoop() # Let wx.App destructor do the cleanup before calling cefpython.Shutdown(). del app cefpython.Shutdown()
def snap(command, width=800, height=600): metadata = {} try: logging.info("Snapshot url: %s" % command['url']) metadata['timestamp'] = int(time()) metadata['error'] = "0" parent_dir = os.path.dirname(command['file']) if parent_dir and not os.path.exists(parent_dir): os.makedirs(parent_dir) if 'screen_width' in command: width = command['screen_width'] if 'screen_height' in command: height = command['screen_height'] cefpython.g_debug = False commandLineSwitches = dict() if 'proxies' in command: proxy = command['proxies'][0] logging.info("Proxy server: %s:1080" % proxy) commandLineSwitches['proxy-server'] = "socks5://" + proxy + ":1080" settings = { "log_severity": cefpython.LOGSEVERITY_DISABLE, # LOGSEVERITY_VERBOSE "log_file": "", "release_dcheck_enabled": False, # Enable only when debugging. # This directories must be set on Linux "locales_dir_path": cefpython.GetModuleDirectory() + "/locales", "resources_dir_path": cefpython.GetModuleDirectory(), "multi_threaded_message_loop": False, "unique_request_context_per_browser": True, "browser_subprocess_path": "%s/%s" % (cefpython.GetModuleDirectory(), "subprocess") } cefpython.Initialize(settings, commandLineSwitches) windowInfo = cefpython.WindowInfo() windowInfo.SetAsOffscreen(0) browserSettings = {"default_encoding": "utf-8"} browser = cefpython.CreateBrowserSync(windowInfo, browserSettings, navigateUrl=command['url']) cookieManager = cefpython.CookieManager.CreateManager("") if 'cookie' in command: for k, v in command['cookie'].items(): cookie = cefpython.Cookie() cookie.SetName(k) cookie.SetValue(v) cookie.SetHasExpires(False) cookieManager.SetCookie(command['url'], cookie) browser.SetUserData("cookieManager", cookieManager) #browser = cefpython.CreateBrowserSync(windowInfo, browserSettings, navigateUrl="about:blank") # TODO handle post data #req = cefpython.Request.CreateRequest() #req.SetUrl(command['url']) # req.SetMethod("POST") # a = req.SetPostData([]) #browser.GetMainFrame().LoadRequest(req) browser.SendFocusEvent(True) browser.SetUserData("width", width) browser.SetUserData("height", height) browser.SetUserData("metadata", metadata) browser.SetClientHandler(ClientHandler(browser, command)) jsBindings = cefpython.JavascriptBindings(bindToFrames=True, bindToPopups=True) jsBindings.SetProperty("delay", int(command['delay'])) jsBindings.SetProperty("flash_delay", int(command['flash_delay'])) jsBindings.SetFunction("setPageSize", setPageSize) jsBindings.SetFunction("jsCallback", jsCallback) jsBindings.SetFunction("log", logging.info) browser.SetJavascriptBindings(jsBindings) #browser.WasResized() cefpython.MessageLoop() width = browser.GetUserData("width") height = browser.GetUserData("height") metadata = browser.GetUserData("metadata") image = browser.GetUserData("image") html = browser.GetUserData("html") except: logging.error(sys.exc_info()) traceback.print_exc() metadata['error'] = str(sys.exc_info()) finally: if metadata['error'] == "0": metadata['status'] = "OK" metadata['finished'] = int(time()) else: metadata['status'] = "error" metadata['time_finished'] = int(time()) cefpython.Shutdown() return width, height, image, html, metadata
def shutdownCEF(): """Shuts down CEF, should be called by app exiting code""" cefpython.Shutdown()