pywin32_postinstall.py 24 KB

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