gooderp18绿色标准版
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

779 lines
27KB

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