Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

pywin32_postinstall.py 27KB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783
  1. # postinstall script for pywin32
  2. #
  3. # copies PyWinTypesxx.dll and PythonCOMxx.dll into the system directory,
  4. # and creates a pth file
  5. import glob
  6. import os
  7. import shutil
  8. import sys
  9. import sysconfig
  10. try:
  11. import winreg as winreg
  12. except:
  13. import winreg
  14. # Send output somewhere so it can be found if necessary...
  15. import tempfile
  16. tee_f = open(os.path.join(tempfile.gettempdir(), "pywin32_postinstall.log"), "w")
  17. class Tee:
  18. def __init__(self, file):
  19. self.f = file
  20. def write(self, what):
  21. if self.f is not None:
  22. try:
  23. self.f.write(what.replace("\n", "\r\n"))
  24. except IOError:
  25. pass
  26. tee_f.write(what)
  27. def flush(self):
  28. if self.f is not None:
  29. try:
  30. self.f.flush()
  31. except IOError:
  32. pass
  33. tee_f.flush()
  34. # For some unknown reason, when running under bdist_wininst we will start up
  35. # with sys.stdout as None but stderr is hooked up. This work-around allows
  36. # bdist_wininst to see the output we write and display it at the end of
  37. # the install.
  38. if sys.stdout is None:
  39. sys.stdout = sys.stderr
  40. sys.stderr = Tee(sys.stderr)
  41. sys.stdout = Tee(sys.stdout)
  42. com_modules = [
  43. # module_name, class_names
  44. ("win32com.servers.interp", "Interpreter"),
  45. ("win32com.servers.dictionary", "DictionaryPolicy"),
  46. ("win32com.axscript.client.pyscript", "PyScript"),
  47. ]
  48. # Is this a 'silent' install - ie, avoid all dialogs.
  49. # Different than 'verbose'
  50. silent = 0
  51. # Verbosity of output messages.
  52. verbose = 1
  53. root_key_name = "Software\\Python\\PythonCore\\" + sys.winver
  54. try:
  55. # When this script is run from inside the bdist_wininst installer,
  56. # file_created() and directory_created() are additional builtin
  57. # functions which write lines to Python23\pywin32-install.log. This is
  58. # a list of actions for the uninstaller, the format is inspired by what
  59. # the Wise installer also creates.
  60. file_created
  61. is_bdist_wininst = True
  62. except NameError:
  63. is_bdist_wininst = False # we know what it is not - but not what it is :)
  64. def file_created(file):
  65. pass
  66. def directory_created(directory):
  67. pass
  68. def get_root_hkey():
  69. try:
  70. winreg.OpenKey(
  71. winreg.HKEY_LOCAL_MACHINE, root_key_name, 0, winreg.KEY_CREATE_SUB_KEY
  72. )
  73. return winreg.HKEY_LOCAL_MACHINE
  74. except OSError:
  75. # Either not exist, or no permissions to create subkey means
  76. # must be HKCU
  77. return winreg.HKEY_CURRENT_USER
  78. try:
  79. create_shortcut
  80. except NameError:
  81. # Create a function with the same signature as create_shortcut provided
  82. # by bdist_wininst
  83. def create_shortcut(
  84. path, description, filename, arguments="", workdir="", iconpath="", iconindex=0
  85. ):
  86. import pythoncom
  87. from win32com.shell import shell
  88. ilink = pythoncom.CoCreateInstance(
  89. shell.CLSID_ShellLink,
  90. None,
  91. pythoncom.CLSCTX_INPROC_SERVER,
  92. shell.IID_IShellLink,
  93. )
  94. ilink.SetPath(path)
  95. ilink.SetDescription(description)
  96. if arguments:
  97. ilink.SetArguments(arguments)
  98. if workdir:
  99. ilink.SetWorkingDirectory(workdir)
  100. if iconpath or iconindex:
  101. ilink.SetIconLocation(iconpath, iconindex)
  102. # now save it.
  103. ipf = ilink.QueryInterface(pythoncom.IID_IPersistFile)
  104. ipf.Save(filename, 0)
  105. # Support the same list of "path names" as bdist_wininst.
  106. def get_special_folder_path(path_name):
  107. from win32com.shell import shell, shellcon
  108. for maybe in """
  109. CSIDL_COMMON_STARTMENU CSIDL_STARTMENU CSIDL_COMMON_APPDATA
  110. CSIDL_LOCAL_APPDATA CSIDL_APPDATA CSIDL_COMMON_DESKTOPDIRECTORY
  111. CSIDL_DESKTOPDIRECTORY CSIDL_COMMON_STARTUP CSIDL_STARTUP
  112. CSIDL_COMMON_PROGRAMS CSIDL_PROGRAMS CSIDL_PROGRAM_FILES_COMMON
  113. CSIDL_PROGRAM_FILES CSIDL_FONTS""".split():
  114. if maybe == path_name:
  115. csidl = getattr(shellcon, maybe)
  116. return shell.SHGetSpecialFolderPath(0, csidl, False)
  117. raise ValueError("%s is an unknown path ID" % (path_name,))
  118. def CopyTo(desc, src, dest):
  119. import win32api
  120. import win32con
  121. while 1:
  122. try:
  123. win32api.CopyFile(src, dest, 0)
  124. return
  125. except win32api.error as details:
  126. if details.winerror == 5: # access denied - user not admin.
  127. raise
  128. if silent:
  129. # Running silent mode - just re-raise the error.
  130. raise
  131. full_desc = (
  132. "Error %s\n\n"
  133. "If you have any Python applications running, "
  134. "please close them now\nand select 'Retry'\n\n%s"
  135. % (desc, details.strerror)
  136. )
  137. rc = win32api.MessageBox(
  138. 0, full_desc, "Installation Error", win32con.MB_ABORTRETRYIGNORE
  139. )
  140. if rc == win32con.IDABORT:
  141. raise
  142. elif rc == win32con.IDIGNORE:
  143. return
  144. # else retry - around we go again.
  145. # We need to import win32api to determine the Windows system directory,
  146. # so we can copy our system files there - but importing win32api will
  147. # load the pywintypes.dll already in the system directory preventing us
  148. # from updating them!
  149. # So, we pull the same trick pywintypes.py does, but it loads from
  150. # our pywintypes_system32 directory.
  151. def LoadSystemModule(lib_dir, modname):
  152. # See if this is a debug build.
  153. import importlib.machinery
  154. import importlib.util
  155. suffix = "_d" if "_d.pyd" in importlib.machinery.EXTENSION_SUFFIXES else ""
  156. filename = "%s%d%d%s.dll" % (
  157. modname,
  158. sys.version_info[0],
  159. sys.version_info[1],
  160. suffix,
  161. )
  162. filename = os.path.join(lib_dir, "pywin32_system32", filename)
  163. loader = importlib.machinery.ExtensionFileLoader(modname, filename)
  164. spec = importlib.machinery.ModuleSpec(name=modname, loader=loader, origin=filename)
  165. mod = importlib.util.module_from_spec(spec)
  166. spec.loader.exec_module(mod)
  167. def SetPyKeyVal(key_name, value_name, value):
  168. root_hkey = get_root_hkey()
  169. root_key = winreg.OpenKey(root_hkey, root_key_name)
  170. try:
  171. my_key = winreg.CreateKey(root_key, key_name)
  172. try:
  173. winreg.SetValueEx(my_key, value_name, 0, winreg.REG_SZ, value)
  174. if verbose:
  175. print("-> %s\\%s[%s]=%r" % (root_key_name, key_name, value_name, value))
  176. finally:
  177. my_key.Close()
  178. finally:
  179. root_key.Close()
  180. def UnsetPyKeyVal(key_name, value_name, delete_key=False):
  181. root_hkey = get_root_hkey()
  182. root_key = winreg.OpenKey(root_hkey, root_key_name)
  183. try:
  184. my_key = winreg.OpenKey(root_key, key_name, 0, winreg.KEY_SET_VALUE)
  185. try:
  186. winreg.DeleteValue(my_key, value_name)
  187. if verbose:
  188. print("-> DELETE %s\\%s[%s]" % (root_key_name, key_name, value_name))
  189. finally:
  190. my_key.Close()
  191. if delete_key:
  192. winreg.DeleteKey(root_key, key_name)
  193. if verbose:
  194. print("-> DELETE %s\\%s" % (root_key_name, key_name))
  195. except OSError as why:
  196. winerror = getattr(why, "winerror", why.errno)
  197. if winerror != 2: # file not found
  198. raise
  199. finally:
  200. root_key.Close()
  201. def RegisterCOMObjects(register=True):
  202. import win32com.server.register
  203. if register:
  204. func = win32com.server.register.RegisterClasses
  205. else:
  206. func = win32com.server.register.UnregisterClasses
  207. flags = {}
  208. if not verbose:
  209. flags["quiet"] = 1
  210. for module, klass_name in com_modules:
  211. __import__(module)
  212. mod = sys.modules[module]
  213. flags["finalize_register"] = getattr(mod, "DllRegisterServer", None)
  214. flags["finalize_unregister"] = getattr(mod, "DllUnregisterServer", None)
  215. klass = getattr(mod, klass_name)
  216. func(klass, **flags)
  217. def RegisterHelpFile(register=True, lib_dir=None):
  218. if lib_dir is None:
  219. lib_dir = sysconfig.get_paths()["platlib"]
  220. if register:
  221. # Register the .chm help file.
  222. chm_file = os.path.join(lib_dir, "PyWin32.chm")
  223. if os.path.isfile(chm_file):
  224. # This isn't recursive, so if 'Help' doesn't exist, we croak
  225. SetPyKeyVal("Help", None, None)
  226. SetPyKeyVal("Help\\Pythonwin Reference", None, chm_file)
  227. return chm_file
  228. else:
  229. print("NOTE: PyWin32.chm can not be located, so has not " "been registered")
  230. else:
  231. UnsetPyKeyVal("Help\\Pythonwin Reference", None, delete_key=True)
  232. return None
  233. def RegisterPythonwin(register=True, lib_dir=None):
  234. """Add (or remove) Pythonwin to context menu for python scripts.
  235. ??? Should probably also add Edit command for pys files also.
  236. Also need to remove these keys on uninstall, but there's no function
  237. like file_created to add registry entries to uninstall log ???
  238. """
  239. import os
  240. if lib_dir is None:
  241. lib_dir = sysconfig.get_paths()["platlib"]
  242. classes_root = get_root_hkey()
  243. ## Installer executable doesn't seem to pass anything to postinstall script indicating if it's a debug build,
  244. pythonwin_exe = os.path.join(lib_dir, "Pythonwin", "Pythonwin.exe")
  245. pythonwin_edit_command = pythonwin_exe + ' -edit "%1"'
  246. keys_vals = [
  247. (
  248. "Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\Pythonwin.exe",
  249. "",
  250. pythonwin_exe,
  251. ),
  252. (
  253. "Software\\Classes\\Python.File\\shell\\Edit with Pythonwin",
  254. "command",
  255. pythonwin_edit_command,
  256. ),
  257. (
  258. "Software\\Classes\\Python.NoConFile\\shell\\Edit with Pythonwin",
  259. "command",
  260. pythonwin_edit_command,
  261. ),
  262. ]
  263. try:
  264. if register:
  265. for key, sub_key, val in keys_vals:
  266. ## Since winreg only uses the character Api functions, this can fail if Python
  267. ## is installed to a path containing non-ascii characters
  268. hkey = winreg.CreateKey(classes_root, key)
  269. if sub_key:
  270. hkey = winreg.CreateKey(hkey, sub_key)
  271. winreg.SetValueEx(hkey, None, 0, winreg.REG_SZ, val)
  272. hkey.Close()
  273. else:
  274. for key, sub_key, val in keys_vals:
  275. try:
  276. if sub_key:
  277. hkey = winreg.OpenKey(classes_root, key)
  278. winreg.DeleteKey(hkey, sub_key)
  279. hkey.Close()
  280. winreg.DeleteKey(classes_root, key)
  281. except OSError as why:
  282. winerror = getattr(why, "winerror", why.errno)
  283. if winerror != 2: # file not found
  284. raise
  285. finally:
  286. # tell windows about the change
  287. from win32com.shell import shell, shellcon
  288. shell.SHChangeNotify(
  289. shellcon.SHCNE_ASSOCCHANGED, shellcon.SHCNF_IDLIST, None, None
  290. )
  291. def get_shortcuts_folder():
  292. if get_root_hkey() == winreg.HKEY_LOCAL_MACHINE:
  293. try:
  294. fldr = get_special_folder_path("CSIDL_COMMON_PROGRAMS")
  295. except OSError:
  296. # No CSIDL_COMMON_PROGRAMS on this platform
  297. fldr = get_special_folder_path("CSIDL_PROGRAMS")
  298. else:
  299. # non-admin install - always goes in this user's start menu.
  300. fldr = get_special_folder_path("CSIDL_PROGRAMS")
  301. try:
  302. install_group = winreg.QueryValue(
  303. get_root_hkey(), root_key_name + "\\InstallPath\\InstallGroup"
  304. )
  305. except OSError:
  306. vi = sys.version_info
  307. install_group = "Python %d.%d" % (vi[0], vi[1])
  308. return os.path.join(fldr, install_group)
  309. # Get the system directory, which may be the Wow64 directory if we are a 32bit
  310. # python on a 64bit OS.
  311. def get_system_dir():
  312. import win32api # we assume this exists.
  313. try:
  314. import pythoncom
  315. import win32process
  316. from win32com.shell import shell, shellcon
  317. try:
  318. if win32process.IsWow64Process():
  319. return shell.SHGetSpecialFolderPath(0, shellcon.CSIDL_SYSTEMX86)
  320. return shell.SHGetSpecialFolderPath(0, shellcon.CSIDL_SYSTEM)
  321. except (pythoncom.com_error, win32process.error):
  322. return win32api.GetSystemDirectory()
  323. except ImportError:
  324. return win32api.GetSystemDirectory()
  325. def fixup_dbi():
  326. # We used to have a dbi.pyd with our .pyd files, but now have a .py file.
  327. # If the user didn't uninstall, they will find the .pyd which will cause
  328. # problems - so handle that.
  329. import win32api
  330. import win32con
  331. pyd_name = os.path.join(os.path.dirname(win32api.__file__), "dbi.pyd")
  332. pyd_d_name = os.path.join(os.path.dirname(win32api.__file__), "dbi_d.pyd")
  333. py_name = os.path.join(os.path.dirname(win32con.__file__), "dbi.py")
  334. for this_pyd in (pyd_name, pyd_d_name):
  335. this_dest = this_pyd + ".old"
  336. if os.path.isfile(this_pyd) and os.path.isfile(py_name):
  337. try:
  338. if os.path.isfile(this_dest):
  339. print(
  340. "Old dbi '%s' already exists - deleting '%s'"
  341. % (this_dest, this_pyd)
  342. )
  343. os.remove(this_pyd)
  344. else:
  345. os.rename(this_pyd, this_dest)
  346. print("renamed '%s'->'%s.old'" % (this_pyd, this_pyd))
  347. file_created(this_pyd + ".old")
  348. except os.error as exc:
  349. print("FAILED to rename '%s': %s" % (this_pyd, exc))
  350. def install(lib_dir):
  351. import traceback
  352. # The .pth file is now installed as a regular file.
  353. # Create the .pth file in the site-packages dir, and use only relative paths
  354. # We used to write a .pth directly to sys.prefix - clobber it.
  355. if os.path.isfile(os.path.join(sys.prefix, "pywin32.pth")):
  356. os.unlink(os.path.join(sys.prefix, "pywin32.pth"))
  357. # The .pth may be new and therefore not loaded in this session.
  358. # Setup the paths just in case.
  359. for name in "win32 win32\\lib Pythonwin".split():
  360. sys.path.append(os.path.join(lib_dir, name))
  361. # It is possible people with old versions installed with still have
  362. # pywintypes and pythoncom registered. We no longer need this, and stale
  363. # entries hurt us.
  364. for name in "pythoncom pywintypes".split():
  365. keyname = "Software\\Python\\PythonCore\\" + sys.winver + "\\Modules\\" + name
  366. for root in winreg.HKEY_LOCAL_MACHINE, winreg.HKEY_CURRENT_USER:
  367. try:
  368. winreg.DeleteKey(root, keyname + "\\Debug")
  369. except WindowsError:
  370. pass
  371. try:
  372. winreg.DeleteKey(root, keyname)
  373. except WindowsError:
  374. pass
  375. LoadSystemModule(lib_dir, "pywintypes")
  376. LoadSystemModule(lib_dir, "pythoncom")
  377. import win32api
  378. # and now we can get the system directory:
  379. files = glob.glob(os.path.join(lib_dir, "pywin32_system32\\*.*"))
  380. if not files:
  381. raise RuntimeError("No system files to copy!!")
  382. # Try the system32 directory first - if that fails due to "access denied",
  383. # it implies a non-admin user, and we use sys.prefix
  384. for dest_dir in [get_system_dir(), sys.prefix]:
  385. # and copy some files over there
  386. worked = 0
  387. try:
  388. for fname in files:
  389. base = os.path.basename(fname)
  390. dst = os.path.join(dest_dir, base)
  391. CopyTo("installing %s" % base, fname, dst)
  392. if verbose:
  393. print("Copied %s to %s" % (base, dst))
  394. # Register the files with the uninstaller
  395. file_created(dst)
  396. worked = 1
  397. # Nuke any other versions that may exist - having
  398. # duplicates causes major headaches.
  399. bad_dest_dirs = [
  400. os.path.join(sys.prefix, "Library\\bin"),
  401. os.path.join(sys.prefix, "Lib\\site-packages\\win32"),
  402. ]
  403. if dest_dir != sys.prefix:
  404. bad_dest_dirs.append(sys.prefix)
  405. for bad_dest_dir in bad_dest_dirs:
  406. bad_fname = os.path.join(bad_dest_dir, base)
  407. if os.path.exists(bad_fname):
  408. # let exceptions go here - delete must succeed
  409. os.unlink(bad_fname)
  410. if worked:
  411. break
  412. except win32api.error as details:
  413. if details.winerror == 5:
  414. # access denied - user not admin - try sys.prefix dir,
  415. # but first check that a version doesn't already exist
  416. # in that place - otherwise that one will still get used!
  417. if os.path.exists(dst):
  418. msg = (
  419. "The file '%s' exists, but can not be replaced "
  420. "due to insufficient permissions. You must "
  421. "reinstall this software as an Administrator" % dst
  422. )
  423. print(msg)
  424. raise RuntimeError(msg)
  425. continue
  426. raise
  427. else:
  428. raise RuntimeError(
  429. "You don't have enough permissions to install the system files"
  430. )
  431. # Pythonwin 'compiles' config files - record them for uninstall.
  432. pywin_dir = os.path.join(lib_dir, "Pythonwin", "pywin")
  433. for fname in glob.glob(os.path.join(pywin_dir, "*.cfg")):
  434. file_created(fname[:-1] + "c") # .cfg->.cfc
  435. # Register our demo COM objects.
  436. try:
  437. try:
  438. RegisterCOMObjects()
  439. except win32api.error as details:
  440. if details.winerror != 5: # ERROR_ACCESS_DENIED
  441. raise
  442. print("You do not have the permissions to install COM objects.")
  443. print("The sample COM objects were not registered.")
  444. except Exception:
  445. print("FAILED to register the Python COM objects")
  446. traceback.print_exc()
  447. # There may be no main Python key in HKCU if, eg, an admin installed
  448. # python itself.
  449. winreg.CreateKey(get_root_hkey(), root_key_name)
  450. chm_file = None
  451. try:
  452. chm_file = RegisterHelpFile(True, lib_dir)
  453. except Exception:
  454. print("Failed to register help file")
  455. traceback.print_exc()
  456. else:
  457. if verbose:
  458. print("Registered help file")
  459. # misc other fixups.
  460. fixup_dbi()
  461. # Register Pythonwin in context menu
  462. try:
  463. RegisterPythonwin(True, lib_dir)
  464. except Exception:
  465. print("Failed to register pythonwin as editor")
  466. traceback.print_exc()
  467. else:
  468. if verbose:
  469. print("Pythonwin has been registered in context menu")
  470. # Create the win32com\gen_py directory.
  471. make_dir = os.path.join(lib_dir, "win32com", "gen_py")
  472. if not os.path.isdir(make_dir):
  473. if verbose:
  474. print("Creating directory %s" % (make_dir,))
  475. directory_created(make_dir)
  476. os.mkdir(make_dir)
  477. try:
  478. # create shortcuts
  479. # CSIDL_COMMON_PROGRAMS only available works on NT/2000/XP, and
  480. # will fail there if the user has no admin rights.
  481. fldr = get_shortcuts_folder()
  482. # If the group doesn't exist, then we don't make shortcuts - its
  483. # possible that this isn't a "normal" install.
  484. if os.path.isdir(fldr):
  485. dst = os.path.join(fldr, "PythonWin.lnk")
  486. create_shortcut(
  487. os.path.join(lib_dir, "Pythonwin\\Pythonwin.exe"),
  488. "The Pythonwin IDE",
  489. dst,
  490. "",
  491. sys.prefix,
  492. )
  493. file_created(dst)
  494. if verbose:
  495. print("Shortcut for Pythonwin created")
  496. # And the docs.
  497. if chm_file:
  498. dst = os.path.join(fldr, "Python for Windows Documentation.lnk")
  499. doc = "Documentation for the PyWin32 extensions"
  500. create_shortcut(chm_file, doc, dst)
  501. file_created(dst)
  502. if verbose:
  503. print("Shortcut to documentation created")
  504. else:
  505. if verbose:
  506. print("Can't install shortcuts - %r is not a folder" % (fldr,))
  507. except Exception as details:
  508. print(details)
  509. # importing win32com.client ensures the gen_py dir created - not strictly
  510. # necessary to do now, but this makes the installation "complete"
  511. try:
  512. import win32com.client # noqa
  513. except ImportError:
  514. # Don't let this error sound fatal
  515. pass
  516. print("The pywin32 extensions were successfully installed.")
  517. if is_bdist_wininst:
  518. # Open a web page with info about the .exe installers being deprecated.
  519. import webbrowser
  520. try:
  521. webbrowser.open("https://mhammond.github.io/pywin32_installers.html")
  522. except webbrowser.Error:
  523. print("Please visit https://mhammond.github.io/pywin32_installers.html")
  524. def uninstall(lib_dir):
  525. # First ensure our system modules are loaded from pywin32_system, so
  526. # we can remove the ones we copied...
  527. LoadSystemModule(lib_dir, "pywintypes")
  528. LoadSystemModule(lib_dir, "pythoncom")
  529. try:
  530. RegisterCOMObjects(False)
  531. except Exception as why:
  532. print("Failed to unregister COM objects: %s" % (why,))
  533. try:
  534. RegisterHelpFile(False, lib_dir)
  535. except Exception as why:
  536. print("Failed to unregister help file: %s" % (why,))
  537. else:
  538. if verbose:
  539. print("Unregistered help file")
  540. try:
  541. RegisterPythonwin(False, lib_dir)
  542. except Exception as why:
  543. print("Failed to unregister Pythonwin: %s" % (why,))
  544. else:
  545. if verbose:
  546. print("Unregistered Pythonwin")
  547. try:
  548. # remove gen_py directory.
  549. gen_dir = os.path.join(lib_dir, "win32com", "gen_py")
  550. if os.path.isdir(gen_dir):
  551. shutil.rmtree(gen_dir)
  552. if verbose:
  553. print("Removed directory %s" % (gen_dir,))
  554. # Remove pythonwin compiled "config" files.
  555. pywin_dir = os.path.join(lib_dir, "Pythonwin", "pywin")
  556. for fname in glob.glob(os.path.join(pywin_dir, "*.cfc")):
  557. os.remove(fname)
  558. # The dbi.pyd.old files we may have created.
  559. try:
  560. os.remove(os.path.join(lib_dir, "win32", "dbi.pyd.old"))
  561. except os.error:
  562. pass
  563. try:
  564. os.remove(os.path.join(lib_dir, "win32", "dbi_d.pyd.old"))
  565. except os.error:
  566. pass
  567. except Exception as why:
  568. print("Failed to remove misc files: %s" % (why,))
  569. try:
  570. fldr = get_shortcuts_folder()
  571. for link in ("PythonWin.lnk", "Python for Windows Documentation.lnk"):
  572. fqlink = os.path.join(fldr, link)
  573. if os.path.isfile(fqlink):
  574. os.remove(fqlink)
  575. if verbose:
  576. print("Removed %s" % (link,))
  577. except Exception as why:
  578. print("Failed to remove shortcuts: %s" % (why,))
  579. # Now remove the system32 files.
  580. files = glob.glob(os.path.join(lib_dir, "pywin32_system32\\*.*"))
  581. # Try the system32 directory first - if that fails due to "access denied",
  582. # it implies a non-admin user, and we use sys.prefix
  583. try:
  584. for dest_dir in [get_system_dir(), sys.prefix]:
  585. # and copy some files over there
  586. worked = 0
  587. for fname in files:
  588. base = os.path.basename(fname)
  589. dst = os.path.join(dest_dir, base)
  590. if os.path.isfile(dst):
  591. try:
  592. os.remove(dst)
  593. worked = 1
  594. if verbose:
  595. print("Removed file %s" % (dst))
  596. except Exception:
  597. print("FAILED to remove %s" % (dst,))
  598. if worked:
  599. break
  600. except Exception as why:
  601. print("FAILED to remove system files: %s" % (why,))
  602. # NOTE: If this script is run from inside the bdist_wininst created
  603. # binary installer or uninstaller, the command line args are either
  604. # '-install' or '-remove'.
  605. # Important: From inside the binary installer this script MUST NOT
  606. # call sys.exit() or raise SystemExit, otherwise not only this script
  607. # but also the installer will terminate! (Is there a way to prevent
  608. # this from the bdist_wininst C code?)
  609. def verify_destination(location):
  610. if not os.path.isdir(location):
  611. raise argparse.ArgumentTypeError('Path "{}" does not exist!'.format(location))
  612. return location
  613. def main():
  614. import argparse
  615. parser = argparse.ArgumentParser(
  616. formatter_class=argparse.RawDescriptionHelpFormatter,
  617. description="""A post-install script for the pywin32 extensions.
  618. * Typical usage:
  619. > python pywin32_postinstall.py -install
  620. If you installed pywin32 via a .exe installer, this should be run
  621. automatically after installation, but if it fails you can run it again.
  622. If you installed pywin32 via PIP, you almost certainly need to run this to
  623. setup the environment correctly.
  624. Execute with script with a '-install' parameter, to ensure the environment
  625. is setup correctly.
  626. """,
  627. )
  628. parser.add_argument(
  629. "-install",
  630. default=False,
  631. action="store_true",
  632. help="Configure the Python environment correctly for pywin32.",
  633. )
  634. parser.add_argument(
  635. "-remove",
  636. default=False,
  637. action="store_true",
  638. help="Try and remove everything that was installed or copied.",
  639. )
  640. parser.add_argument(
  641. "-wait",
  642. type=int,
  643. help="Wait for the specified process to terminate before starting.",
  644. )
  645. parser.add_argument(
  646. "-silent",
  647. default=False,
  648. action="store_true",
  649. help='Don\'t display the "Abort/Retry/Ignore" dialog for files in use.',
  650. )
  651. parser.add_argument(
  652. "-quiet",
  653. default=False,
  654. action="store_true",
  655. help="Don't display progress messages.",
  656. )
  657. parser.add_argument(
  658. "-destination",
  659. default=sysconfig.get_paths()["platlib"],
  660. type=verify_destination,
  661. help="Location of the PyWin32 installation",
  662. )
  663. args = parser.parse_args()
  664. if not args.quiet:
  665. print("Parsed arguments are: {}".format(args))
  666. if not args.install ^ args.remove:
  667. parser.error("You need to either choose to -install or -remove!")
  668. if args.wait is not None:
  669. try:
  670. os.waitpid(args.wait, 0)
  671. except os.error:
  672. # child already dead
  673. pass
  674. silent = args.silent
  675. verbose = not args.quiet
  676. if args.install:
  677. install(args.destination)
  678. if args.remove:
  679. if not is_bdist_wininst:
  680. uninstall(args.destination)
  681. if __name__ == "__main__":
  682. main()