lucy-python-script-2030 0.1.0__py3-none-any.whl

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