Skip to content

Commit a7661ba

Browse files
committed
Updating pywin32 example (wip)
1 parent 483dcaf commit a7661ba

File tree

1 file changed

+44
-91
lines changed

1 file changed

+44
-91
lines changed

examples/pywin32.py

Lines changed: 44 additions & 91 deletions
Original file line numberDiff line numberDiff line change
@@ -1,95 +1,47 @@
11
# Example of embedding CEF browser using the PyWin32 extension.
2-
# Tested with pywin32 version 218.
3-
4-
import os, sys
5-
libcef_dll = os.path.join(os.path.dirname(os.path.abspath(__file__)),
6-
'libcef.dll')
7-
if os.path.exists(libcef_dll):
8-
# Import a local module
9-
if (2,7) <= sys.version_info < (2,8):
10-
import cefpython_py27 as cefpython
11-
elif (3,4) <= sys.version_info < (3,4):
12-
import cefpython_py34 as cefpython
13-
else:
14-
raise Exception("Unsupported python version: %s" % sys.version)
15-
else:
16-
# Import an installed package
17-
from cefpython3 import cefpython
2+
# Tested with pywin32 version 219.
3+
4+
from cefpython3 import cefpython as cef
5+
6+
import distutils.sysconfig
7+
import os
8+
import platform
9+
import sys
10+
import time
1811

19-
import cefwindow
12+
import win32api
2013
import win32con
2114
import win32gui
22-
import win32api
23-
import time
2415

25-
DEBUG = True
26-
27-
# -----------------------------------------------------------------------------
28-
# Helper functions.
29-
30-
def Log(msg):
31-
print("[pywin32.py] %s" % str(msg))
32-
33-
def GetApplicationPath(file=None):
34-
import re, os, platform
35-
# On Windows after downloading file and calling Browser.GoForward(),
36-
# current working directory is set to %UserProfile%.
37-
# Calling os.path.dirname(os.path.realpath(__file__))
38-
# returns for eg. "C:\Users\user\Downloads". A solution
39-
# is to cache path on first call.
40-
if not hasattr(GetApplicationPath, "dir"):
41-
if hasattr(sys, "frozen"):
42-
dir = os.path.dirname(sys.executable)
43-
elif "__file__" in globals():
44-
dir = os.path.dirname(os.path.realpath(__file__))
45-
else:
46-
dir = os.getcwd()
47-
GetApplicationPath.dir = dir
48-
# If file is None return current directory without trailing slash.
49-
if file is None:
50-
file = ""
51-
# Only when relative path.
52-
if not file.startswith("/") and not file.startswith("\\") and (
53-
not re.search(r"^[\w-]+:", file)):
54-
path = GetApplicationPath.dir + os.sep + file
55-
if platform.system() == "Windows":
56-
path = re.sub(r"[/\\]+", re.escape(os.sep), path)
57-
path = re.sub(r"[/\\]+$", "", path)
58-
return path
59-
return str(file)
60-
61-
def ExceptHook(excType, excValue, traceObject):
62-
import traceback, os, time, codecs
63-
# This hook does the following: in case of exception write it to
64-
# the "error.log" file, display it to the console, shutdown CEF
65-
# and exit application immediately by ignoring "finally" (os._exit()).
66-
errorMsg = "\n".join(traceback.format_exception(excType, excValue,
67-
traceObject))
68-
errorFile = GetApplicationPath("error.log")
69-
try:
70-
appEncoding = cefpython.g_applicationSettings["string_encoding"]
71-
except:
72-
appEncoding = "utf-8"
73-
if type(errorMsg) == bytes:
74-
errorMsg = errorMsg.decode(encoding=appEncoding, errors="replace")
75-
try:
76-
with codecs.open(errorFile, mode="a", encoding=appEncoding) as fp:
77-
fp.write("\n[%s] %s\n" % (
78-
time.strftime("%Y-%m-%d %H:%M:%S"), errorMsg))
79-
except:
80-
print("[pywin32.py] WARNING: failed writing to error file: %s" % (
81-
errorFile))
82-
# Convert error message to ascii before printing, otherwise
83-
# you may get error like this:
84-
# | UnicodeEncodeError: 'charmap' codec can't encode characters
85-
errorMsg = errorMsg.encode("ascii", errors="replace")
86-
errorMsg = errorMsg.decode("ascii", errors="replace")
87-
print("\n"+errorMsg+"\n")
88-
cefpython.QuitMessageLoop()
89-
cefpython.Shutdown()
90-
os._exit(1)
16+
WindowUtils = cef.WindowUtils()
17+
18+
# Platforms (Windows only)
19+
assert(platform.system() == "Windows")
20+
21+
def main():
22+
check_versions()
23+
sys.excepthook = cef.ExceptHook # To shutdown all CEF processes on error
24+
cef.Initialize()
25+
pyWin32Example()
26+
"""
27+
if g_message_loop == MESSAGE_LOOP_CEF:
28+
cef.MessageLoop()
29+
else:
30+
gtk.main()
31+
"""
32+
cef.Shutdown()
33+
34+
35+
def check_versions():
36+
print("[pywin32.py] CEF Python {ver}".format(ver=cef.__version__))
37+
print("[pywin32.py] Python {ver} {arch}".format(ver=platform.python_version(), arch=platform.architecture()[0]))
38+
print("[pywin32.py] pywin32 {ver}".format(ver=GetPywin32Version()))
39+
assert cef.__version__ >= "55.3", "CEF Python v55.3+ required to run this"
40+
41+
42+
def pyWin32Example():
43+
pass
9144

92-
# -----------------------------------------------------------------------------
9345

9446
def CefAdvanced():
9547
sys.excepthook = ExceptHook
@@ -144,9 +96,10 @@ def QuitApplication(windowHandle, message, wparam, lparam):
14496
return 0
14597

14698
def GetPywin32Version():
147-
fixed_file_info = win32api.GetFileVersionInfo(win32api.__file__, '\\')
148-
return fixed_file_info['FileVersionLS'] >> 16
99+
pth = distutils.sysconfig.get_python_lib(plat_specific=1)
100+
ver = open(os.path.join(pth, "pywin32.version.txt")).read().strip()
101+
return ver
102+
149103

150-
if __name__ == "__main__":
151-
Log("pywin32 version = %s" % GetPywin32Version())
152-
CefAdvanced()
104+
if __name__ == '__main__':
105+
main()

0 commit comments

Comments
 (0)