forked from mhammond/pywin32
-
Notifications
You must be signed in to change notification settings - Fork 0
/
setup.py
2301 lines (2137 loc) · 93.6 KB
/
setup.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
build_id = "308.1" # may optionally include a ".{patchno}" suffix.
__doc__ = """This is a distutils setup-script for the pywin32 extensions.
The canonical source of truth for supported versions and build environments
is [the GitHub CI](https://github.com/mhammond/pywin32/tree/main/.github/workflows).
To build and install locally for testing etc, you need a build environment
which is capable of building the version of Python you are targeting, then:
python setup.py -q install
For a debug (_d) version, you need a local debug build of Python, but must use
the release version executable for the build. eg:
python setup.py -q build --debug install
Cross-compilation from x86 to ARM is well supported (assuming installed vs tools etc) - eg:
python setup.py -q build_ext --plat-name win-arm64 build --plat-name win-arm64 bdist_wheel --plat-name win-arm64
Some modules require special SDKs or toolkits to build (eg, mapi/exchange),
which often aren't available in CI. The build process treats them as optional -
instead of a failing, it will report what was skipped, and why. See also
build_env.md, which is getting out of date but might help getting everything
required for an official build - see README.md for that process.
"""
# Originally by Thomas Heller, started in 2000 or so.
import glob
import logging
import os
import platform
import re
import shutil
import subprocess
import sys
import winreg
from pathlib import Path
from setuptools import Extension, setup
from setuptools.command.build import build
from setuptools.command.build_ext import build_ext
from setuptools.command.install import install
from setuptools.command.install_lib import install_lib
from setuptools.modified import newer_group
from tempfile import gettempdir
from typing import Iterable
from distutils import ccompiler
from distutils._msvccompiler import MSVCCompiler
from distutils.command.install_data import install_data
build_id_patch = build_id
if not "." in build_id_patch:
build_id_patch += ".0"
pywin32_version = "%d.%d.%s" % (
sys.version_info.major,
sys.version_info.minor,
build_id_patch,
)
print("Building pywin32", pywin32_version)
try:
this_file = __file__
except NameError:
this_file = sys.argv[0]
this_file = os.path.abspath(this_file)
# We get upset if the cwd is not our source dir, but it is a PITA to
# insist people manually CD there first!
if os.path.dirname(this_file):
os.chdir(os.path.dirname(this_file))
# Start address we assign base addresses from. See comment re
# dll_base_address later in this file...
dll_base_address = 0x1E200000
class WinExt(Extension):
# Base class for all win32 extensions, with some predefined
# library and include dirs, and predefined windows libraries.
# Additionally a method to parse .def files into lists of exported
# symbols, and to read
def __init__(
self,
name,
sources,
include_dirs=[],
define_macros=None,
undef_macros=None,
library_dirs=[],
libraries="",
runtime_library_dirs=None,
extra_objects=None,
extra_compile_args=None,
extra_link_args=None,
export_symbols=None,
export_symbol_file=None,
pch_header=None,
windows_h_version=None, # min version of windows.h needed.
extra_swig_commands=None,
is_regular_dll=False, # regular Windows DLL?
# list of headers which may not be installed forcing us to
# skip this extension
optional_headers=[],
base_address=None,
depends=None,
platforms=None, # none means 'all platforms'
implib_name=None,
delay_load_libraries="",
):
include_dirs = ["com/win32com/src/include", "win32/src"] + include_dirs
libraries = libraries.split()
self.delay_load_libraries = delay_load_libraries.split()
libraries.extend(self.delay_load_libraries)
extra_link_args = extra_link_args or []
if export_symbol_file:
extra_link_args.append("/DEF:" + export_symbol_file)
# Some of our swigged files behave differently in distutils vs
# MSVC based builds. Always define DISTUTILS_BUILD so they can tell.
define_macros = define_macros or []
define_macros.append(("DISTUTILS_BUILD", None))
define_macros.append(("_CRT_SECURE_NO_WARNINGS", None))
# CRYPT_DECRYPT_MESSAGE_PARA.dwflags is in an ifdef for some unknown reason
# See github PR #1444 for more details...
define_macros.append(("CRYPT_DECRYPT_MESSAGE_PARA_HAS_EXTRA_FIELDS", None))
self.pch_header = pch_header
self.extra_swig_commands = extra_swig_commands or []
self.windows_h_version = windows_h_version
self.optional_headers = optional_headers
self.is_regular_dll = is_regular_dll
self.base_address = base_address
self.platforms = platforms
self.implib_name = implib_name
Extension.__init__(
self,
name,
sources,
include_dirs,
define_macros,
undef_macros,
library_dirs,
libraries,
runtime_library_dirs,
extra_objects,
extra_compile_args,
extra_link_args,
export_symbols,
)
self.depends = depends or [] # stash it here, as py22 doesn't have it.
def finalize_options(self, build_ext):
# distutils doesn't define this function for an Extension - it is
# our own invention, and called just before the extension is built.
if not build_ext.mingw32:
if self.pch_header:
self.extra_compile_args = self.extra_compile_args or []
# bugger - add this to python!
if build_ext.plat_name == "win32":
self.extra_link_args.append("/MACHINE:x86")
else:
self.extra_link_args.append("/MACHINE:%s" % build_ext.plat_name[4:])
# like Python, always use debug info, even in release builds
# (note the compiler doesn't include debug info, so you only get
# basic info - but it's better than nothing!)
# For now use the temp dir - later we may package them, so should
# maybe move them next to the output file.
pch_dir = os.path.join(build_ext.build_temp)
if not build_ext.debug:
self.extra_compile_args.append("/Zi")
self.extra_compile_args.append(f"/Fd{pch_dir}\\{self.name}_vc.pdb")
self.extra_link_args.append("/DEBUG")
self.extra_link_args.append(f"/PDB:{pch_dir}\\{self.name}.pdb")
# enable unwind semantics - some stuff needs it and I can't see
# it hurting
self.extra_compile_args.append("/EHsc")
# silence: warning C4163: '__cpuidex' : not available as an intrinsic function
self.extra_compile_args.append("/wd4163")
if self.delay_load_libraries:
self.libraries.append("delayimp")
for delay_lib in self.delay_load_libraries:
self.extra_link_args.append("/delayload:%s.dll" % delay_lib)
# If someone needs a specially named implib created, handle that
if self.implib_name:
implib = os.path.join(build_ext.build_temp, self.implib_name)
suffix = "_d" if build_ext.debug else ""
self.extra_link_args.append(f"/IMPLIB:{implib}{suffix}.lib")
# Try and find the MFC headers, so we can reach inside for
# some of the ActiveX support we need. We need to do this late, so
# the environment is setup correctly.
# Only used by the win32uiole extensions, but I can't be
# bothered making a subclass just for this - so they all get it!
found_mfc = False
for incl in os.environ.get("INCLUDE", "").split(os.pathsep):
# first is a "standard" MSVC install, second is the Vista SDK.
for candidate in (r"..\src\occimpl.h", r"..\..\src\mfc\occimpl.h"):
check = os.path.join(incl, candidate)
if os.path.isfile(check):
self.extra_compile_args.append(
'/DMFC_OCC_IMPL_H=\\"%s\\"' % candidate
)
found_mfc = True
break
if found_mfc:
break
self.extra_compile_args.append("-DUNICODE")
self.extra_compile_args.append("-D_UNICODE")
self.extra_compile_args.append("-DWINNT")
class WinExt_pythonwin(WinExt):
def __init__(self, name, **kw):
kw.setdefault("extra_compile_args", []).extend(["-D_AFXDLL", "-D_AFXEXT"])
WinExt.__init__(self, name, **kw)
def get_pywin32_dir(self):
return "pythonwin"
class WinExt_pythonwin_subsys_win(WinExt_pythonwin):
def finalize_options(self, build_ext):
WinExt_pythonwin.finalize_options(self, build_ext)
if build_ext.mingw32:
self.extra_link_args.append("-mwindows")
else:
self.extra_link_args.append("/SUBSYSTEM:WINDOWS")
# Unicode, Windows executables seem to need this magic:
self.extra_link_args.append("/ENTRY:wWinMainCRTStartup")
class WinExt_win32(WinExt):
def __init__(self, name, **kw):
WinExt.__init__(self, name, **kw)
def get_pywin32_dir(self):
return "win32"
class WinExt_ISAPI(WinExt):
def get_pywin32_dir(self):
return "isapi"
# Note this is used only for "win32com extensions", not pythoncom
# itself - thus, output is "win32comext"
class WinExt_win32com(WinExt):
def __init__(self, name, **kw):
kw["libraries"] = kw.get("libraries", "") + " oleaut32 ole32"
# COM extensions require later windows headers.
if not kw.get("windows_h_version"):
kw["windows_h_version"] = 0x500
WinExt.__init__(self, name, **kw)
def get_pywin32_dir(self):
return "win32comext/" + self.name
# Exchange extensions get special treatment:
# * Look for the Exchange SDK in the registry.
# * Output directory is different than the module's basename.
# * Require use of the Exchange 2000 SDK - this works for both VC6 and 7
# NOTE: sadly the old Exchange SDK does *not* include MAPI files - these used
# to be bundled with the Windows SDKs and/or Visual Studio, but no longer are.
class WinExt_win32com_mapi(WinExt_win32com):
def __init__(self, name, **kw):
# The Exchange 2000 SDK seems to install itself without updating
# LIB or INCLUDE environment variables. It does register the core
# directory in the registry tho - look it up
sdk_install_dir = None
libs = kw.get("libraries", "")
keyname = r"SOFTWARE\Microsoft\Exchange\SDK"
flags = winreg.KEY_READ
try:
flags |= winreg.KEY_WOW64_32KEY
except AttributeError:
pass # this version doesn't support 64 bits, so must already be using 32bit key.
for root in winreg.HKEY_LOCAL_MACHINE, winreg.HKEY_CURRENT_USER:
try:
keyob = winreg.OpenKey(root, keyname, 0, flags)
value, type_id = winreg.QueryValueEx(keyob, "INSTALLDIR")
if type_id == winreg.REG_SZ:
sdk_install_dir = value
break
except OSError:
pass
if sdk_install_dir is not None:
d = os.path.join(sdk_install_dir, "SDK", "Include")
if os.path.isdir(d):
kw.setdefault("include_dirs", []).insert(0, d)
d = os.path.join(sdk_install_dir, "SDK", "Lib")
if os.path.isdir(d):
kw.setdefault("library_dirs", []).insert(0, d)
# The stand-alone exchange SDK has these libs
# Additional utility functions are only available for 32-bit builds.
if not platform.machine() in ("AMD64", "ARM64"):
libs += " version user32 advapi32 Ex2KSdk sadapi netapi32"
kw["libraries"] = libs
WinExt_win32com.__init__(self, name, **kw)
def get_pywin32_dir(self):
# 'win32com.mapi.exchange' is currently the only
# one with this special requirement
return "win32comext/mapi"
# A hacky extension class for pywintypesXX.dll and pythoncomXX.dll
class WinExt_system32(WinExt):
def get_pywin32_dir(self):
return "pywin32_system32"
class WinExt_pythonservice(WinExt):
# special handling because it's a "console" exe.
def finalize_options(self, build_ext):
WinExt.finalize_options(self, build_ext)
if build_ext.mingw32:
self.extra_link_args.append("-mconsole")
self.extra_link_args.append("-municode")
else:
self.extra_link_args.append("/SUBSYSTEM:CONSOLE")
# pythonservice.exe goes in win32, where it doesn't actually work, but
# win32serviceutil manages to copy it to where it does.
def get_pywin32_dir(self):
return "win32"
################################################################
# Extensions to the distutils commands.
# 'build' command
class my_build(build):
def run(self):
build.run(self)
# write a pywin32.version.txt.
ver_fname = os.path.join(gettempdir(), "pywin32.version.txt")
try:
f = open(ver_fname, "w")
f.write("%s\n" % build_id)
f.close()
except OSError as why:
print(f"Failed to open '{ver_fname}': {why}")
class my_build_ext(build_ext):
def finalize_options(self):
build_ext.finalize_options(self)
self.plat_dir = {
"win-amd64": "x64",
"win-arm64": "arm64",
}.get(self.plat_name, "x86")
self.windows_h_version = None
# The pywintypes library is created in the build_temp
# directory, so we need to add this to library_dirs
self.library_dirs.append(self.build_temp)
self.mingw32 = self.compiler == "mingw32"
if self.mingw32:
self.libraries.append("stdc++")
self.excluded_extensions = [] # list of (ext, why)
self.swig_cpp = True # hrm - deprecated - should use swig_opts=-c++??
def _why_cant_build_extension(self, ext):
"""Return None, or a reason it can't be built."""
# axdebug fails to build on 3.11 due to Python "frame" objects changing.
# This could be fixed, but is almost certainly not in use any more, so
# just skip it.
if ext.name == "axdebug" and sys.version_info > (3, 10):
return "AXDebug no longer builds on 3.11 and up"
include_dirs = self.compiler.include_dirs + os.environ.get("INCLUDE", "").split(
os.pathsep
)
if self.windows_h_version is None:
# Note that we used to try and find WINVER or _WIN32_WINNT macros
# here defining the version of the Windows SDK we use and check
# it was late enough for the extension being built. But since we
# moved to the Windows 8.1 SDK (or later), this isn't necessary
# as all modules require less than this.
pass
look_dirs = include_dirs
for h in ext.optional_headers:
for d in look_dirs:
if os.path.isfile(os.path.join(d, h)):
break
else:
logging.debug("Header '%s' not found in %s", h, look_dirs)
return f"The header '{h}' can not be located."
common_dirs = self.compiler.library_dirs[:]
common_dirs += os.environ.get("LIB", "").split(os.pathsep)
patched_libs = []
for lib in ext.libraries:
if lib.lower() in self.found_libraries:
found = self.found_libraries[lib.lower()]
else:
look_dirs = common_dirs + ext.library_dirs
found = self.compiler.find_library_file(look_dirs, lib, self.debug)
if not found:
logging.debug("Lib '%s' not found in %s", lib, look_dirs)
return "No library '%s'" % lib
self.found_libraries[lib.lower()] = found
patched_libs.append(os.path.splitext(os.path.basename(found))[0])
if ext.platforms and self.plat_name not in ext.platforms:
return f"Only available on platforms {ext.platforms}"
# We update the .libraries list with the resolved library name.
# This is really only so "_d" works.
ext.libraries = patched_libs
return None # no reason - it can be built!
def _build_scintilla(self):
path = "pythonwin\\Scintilla"
makefile = "makefile_pythonwin"
makeargs = []
if self.debug:
makeargs.append("DEBUG=1")
if not self.verbose:
makeargs.append("/C") # nmake: /C Suppress output messages
makeargs.append("QUIET=1")
# We build the DLL into our own temp directory, then copy it to the
# real directory - this avoids the generated .lib/.exp
build_temp = os.path.abspath(os.path.join(self.build_temp, "scintilla"))
self.mkpath(build_temp)
# Use short-names, as the scintilla makefiles barf with spaces.
if " " in build_temp:
# ack - can't use win32api!!! This is the best I could come up
# with:
# C:\>for %I in ("C:\Program Files",) do @echo %~sI
# C:\PROGRA~1
cs = os.environ.get("comspec", "cmd.exe")
cmd = cs + ' /c for %I in ("' + build_temp + '",) do @echo %~sI'
build_temp = os.popen(cmd).read().strip()
assert os.path.isdir(build_temp), build_temp
makeargs.append("SUB_DIR_O=%s" % build_temp)
makeargs.append("SUB_DIR_BIN=%s" % build_temp)
makeargs.append("DIR_PYTHON=%s" % sys.prefix)
nmake = "nmake.exe"
# Attempt to resolve nmake to the same one that our compiler object
# would use. compiler.spawn() ought to do this, but it does not search
# its own PATH value for the initial command. It does, however, set it
# correctly for any subsequent commands.
try:
for p in self.compiler._paths.split(os.pathsep):
if os.path.isfile(os.path.join(p, nmake)):
nmake = os.path.join(p, nmake)
break
except (AttributeError, TypeError):
pass
cwd = os.getcwd()
old_env = os.environ.copy()
os.environ["INCLUDE"] = os.pathsep.join(self.compiler.include_dirs)
os.environ["LIB"] = os.pathsep.join(self.compiler.library_dirs)
os.chdir(path)
try:
cmd = [nmake, "/nologo", "/f", makefile] + makeargs
self.compiler.spawn(cmd)
finally:
os.chdir(cwd)
os.environ["INCLUDE"] = old_env.get("INCLUDE", "")
os.environ["LIB"] = old_env.get("LIB", "")
# The DLL goes in the Pythonwin directory.
if self.debug:
base_name = "scintilla_d.dll"
else:
base_name = "scintilla.dll"
self.copy_file(
os.path.join(self.build_temp, "scintilla", base_name),
os.path.join(self.build_lib, "pythonwin"),
)
# find the VC base path corresponding to distutils paths, and
# potentially upgrade for extra include / lib paths (MFC)
def _check_vc(self):
vcbase = vcverdir = None
atlmfc_found = False
for _dir in self.compiler.library_dirs:
m = re.search(r"(?i)VC\\([\d.]+\\)?(LIB)\b", _dir)
if m and not vcbase:
vcbase = _dir[: m.start(2)]
vcverdir = m.group(1)
m = re.search(r"(?i)ATLMFC\\LIB\b", _dir)
if m:
atlmfc_found = True # ATLMFC libs/includes already found by distutils
if not vcbase and not self.mingw32:
print("-- compiler.library_dirs:", self.compiler.library_dirs)
# Error or warn? last hope would be a non-standard build environment
print("-- Visual C base path not found !?")
# The afxres.h/atls.lib files aren't always included by default,
# so find and add them
if vcbase and not atlmfc_found:
atls_lib = glob.glob(vcbase + rf"ATLMFC\lib\{self.plat_dir}\atls.lib")
if atls_lib:
self.library_dirs.append(os.path.dirname(atls_lib[0]))
self.include_dirs.append(
os.path.join(
os.path.dirname(os.path.dirname(os.path.dirname(atls_lib[0]))),
"Include",
)
)
else:
print("-- compiler.library_dirs:", self.compiler.library_dirs)
print("-- ATLMFC paths likely missing (Required for win32ui)")
return vcbase, vcverdir
def build_extensions(self):
# First, sanity-check the 'extensions' list
self.check_extensions_list(self.extensions)
self.found_libraries = {}
if hasattr(self.compiler, "initialize") and not self.compiler.initialized:
self.compiler.initialize()
# XXX this distutils class var peek hack should become obsolete
# (silently) when https://github.com/pypa/distutils/pull/172 is
# resolved.
# _why_cant_build_extension() and _build_scintilla() at least need
# complete VC+SDK inspectable inc / lib dirs.
classincs = getattr(self.compiler.__class__, "include_dirs", [])
if classincs:
print("-- distutils hack to expose all include & lib dirs")
print("-- orig compiler.include_dirs:", self.compiler.include_dirs)
print("-- orig compiler.library_dirs:", self.compiler.library_dirs)
self.compiler.include_dirs += classincs
self.compiler.__class__.include_dirs = []
classlibs = getattr(self.compiler.__class__, "library_dirs", [])
self.compiler.library_dirs += classlibs
self.compiler.__class__.library_dirs = []
else:
print("-- FIX ME ! distutils may expose complete inc/lib dirs again")
vcbase, vcverdir = self._check_vc()
# Here we hack a "pywin32" directory (one of 'win32', 'win32com',
# 'pythonwin' etc), as distutils doesn't seem to like the concept
# of multiple top-level directories.
assert self.package is None
for ext in self.extensions:
try:
self.package = ext.get_pywin32_dir()
except AttributeError:
raise RuntimeError("Not a win32 package!")
self.build_extension(ext)
for ext in W32_exe_files:
self.package = ext.get_pywin32_dir()
ext.finalize_options(self)
why = self._why_cant_build_extension(ext)
if why is not None:
self.excluded_extensions.append((ext, why))
assert why, "please give a reason, or None"
print(f"Skipping {ext.name}: {why}")
continue
self.build_exefile(ext)
# Error when too many skips
if len(self.excluded_extensions) > 0.3 * (
len(self.extensions) + len(W32_exe_files)
):
print("-- compiler.include_dirs:", self.compiler.include_dirs)
print("-- compiler.library_dirs:", self.compiler.library_dirs)
raise RuntimeError("Too many extensions skipped, check build environment")
# Not sure how to make this completely generic, and there is no
# need at this stage.
self._build_scintilla()
# Copy cpp lib files needed to create Python COM extensions
clib_files = (
["win32", "pywintypes%s.lib"],
["win32com", "pythoncom%s.lib"],
["win32com", "axscript%s.lib"],
)
for clib_file in clib_files:
target_dir = os.path.join(self.build_lib, clib_file[0], "libs")
if not os.path.exists(target_dir):
self.mkpath(target_dir)
suffix = "_d" if self.debug else ""
fname = clib_file[1] % suffix
self.copy_file(os.path.join(self.build_temp, fname), target_dir)
# Finally find and copy the MFC redistributable DLLs.
win32ui_ext = pythonwin_extensions[0]
if win32ui_ext not in set(self.extensions) - {
ext for ext, why in self.excluded_extensions
}:
return
if not vcbase:
raise RuntimeError("Can't find MFC redist DLLs with unkown VC base path")
redist_globs = [vcbase + r"redist\%s\*MFC\mfc140u.dll" % self.plat_dir]
m = re.search(r"\\VC\\Tools\\", vcbase)
if m:
# typical path on newer Visual Studios
# prefere corresponding version but accept different version
same_version = vcverdir is not None and os.path.isdir(
vcbase[: m.start()]
+ r"\VC\Redist\MSVC\{}{}".format(vcverdir, self.plat_dir)
)
redist_globs.append(
vcbase[: m.start()]
+ r"\VC\Redist\MSVC\{}{}\*\mfc140u.dll".format(
vcverdir if same_version else "*\\", self.plat_dir
)
)
# Only mfcNNNu DLL is required (mfcmNNNX is Windows Forms, rest is ANSI)
mfc_contents = next(filter(None, map(glob.glob, redist_globs)), [])[:1]
if not mfc_contents:
raise RuntimeError("MFC redist DLLs not found like %r!" % redist_globs)
target_dir = os.path.join(self.build_lib, win32ui_ext.get_pywin32_dir())
for mfc_content in mfc_contents:
self.copy_file(mfc_content, target_dir)
def build_exefile(self, ext):
suffix = "_d" if self.debug else ""
logging.info("building exe '%s'", ext.name)
leaf_name = f"{ext.get_pywin32_dir()}\\{ext.name}{suffix}.exe"
full_name = os.path.join(self.build_lib, leaf_name)
sources = list(ext.sources)
depends = sources + ext.depends
# unclear why we need to check this!?
if not (self.force or newer_group(depends, full_name, "newer")):
logging.debug("skipping '%s' executable (up-to-date)", ext.name)
return
else:
logging.info("building '%s' executable", ext.name)
objects = self.compiler.compile(
sources,
output_dir=os.path.join(self.build_temp, ext.name),
include_dirs=ext.include_dirs,
debug=self.debug,
extra_postargs=ext.extra_compile_args,
depends=ext.depends,
)
self.compiler.link(
"executable",
objects,
full_name,
libraries=self.get_libraries(ext),
library_dirs=ext.library_dirs,
runtime_library_dirs=ext.runtime_library_dirs,
extra_postargs=ext.extra_link_args,
debug=self.debug,
build_temp=self.build_temp,
)
def build_extension(self, ext):
# Some of these extensions are difficult to build, requiring various
# hard-to-track libraries et (eg, exchange sdk, etc). So we
# check the extension list for the extra libraries explicitly
# listed. We then search for this library the same way the C
# compiler would - if we can't find a library, we exclude the
# extension from the build.
# Note we can't do this in advance, as some of the .lib files
# we depend on may be built as part of the process - thus we can
# only check an extension's lib files as we are building it.
why = self._why_cant_build_extension(ext)
if why is not None:
assert why, "please give a reason, or None"
self.excluded_extensions.append((ext, why))
print(f"Skipping {ext.name}: {why}")
return
self.current_extension = ext
ext.finalize_options(self)
# ensure the SWIG .i files are treated as dependencies.
for source in ext.sources:
if source.endswith(".i"):
self.find_swig() # for the side-effect of the environment value.
# Find the swig_lib .i files we care about for dependency tracking.
ext.swig_deps = glob.glob(
os.path.join(os.environ["SWIG_LIB"], "python", "*.i")
)
ext.depends.extend(ext.swig_deps)
break
else:
ext.swig_deps = None
# some source files are compiled for different extensions
# with special defines. So we cannot use a shared
# directory for objects, we must use a special one for each extension.
old_build_temp = self.build_temp
try:
build_ext.build_extension(self, ext)
# Convincing distutils to create .lib files with the name we
# need is difficult, so we just hack around it by copying from
# the created name to the name we need.
extra = "_d.lib" if self.debug else ".lib"
if ext.name in ("pywintypes", "pythoncom"):
# The import libraries are created as PyWinTypes23.lib, but
# are expected to be pywintypes.lib.
created = "%s%d%d%s" % (
ext.name,
sys.version_info.major,
sys.version_info.minor,
extra,
)
needed = f"{ext.name}{extra}"
elif ext.name in ("win32ui",):
# This one just needs a copy.
created = needed = ext.name + extra
else:
created = needed = None
if created is not None:
# To keep us on our toes, MSVCCompiler constructs the .lib files
# in the same directory as the first source file's object file:
# os.path.dirname(objects[0])
# rather than in the self.build_temp directory
src = os.path.join(
old_build_temp, os.path.dirname(ext.sources[0]), created
)
dst = os.path.join(old_build_temp, needed)
if os.path.abspath(src) != os.path.abspath(dst):
self.copy_file(src, dst)
finally:
self.build_temp = old_build_temp
def get_ext_filename(self, name):
# We need to fixup some target filenames.
suffix = "_d" if self.debug else ""
if name in ["pywintypes", "pythoncom"]:
ver = f"{sys.version_info.major}{sys.version_info.minor}"
return f"{name}{ver}{suffix}.dll"
if name in ["perfmondata", "PyISAPI_loader"]:
return f"{name}{suffix}.dll"
# everything else a .pyd - calling base-class might give us a more
# complicated name, so return a simple one.
return f"{name}{suffix}.pyd"
def get_export_symbols(self, ext):
if ext.is_regular_dll:
return ext.export_symbols
return build_ext.get_export_symbols(self, ext)
def find_swig(self):
if "SWIG" in os.environ:
swig = os.environ["SWIG"]
else:
# We know where our swig is
swig = os.path.abspath("swig\\swig.exe")
lib = os.path.join(os.path.dirname(swig), "swig_lib")
os.environ["SWIG_LIB"] = lib
return swig
def swig_sources(self, sources, ext=None):
new_sources = []
swig_sources = []
swig_targets = {}
# XXX this drops generated C/C++ files into the source tree, which
# is fine for developers who want to distribute the generated
# source -- but there should be an option to put SWIG output in
# the temp dir.
# Adding py3k to the mix means we *really* need to move to generating
# to the temp dir...
target_ext = ".cpp"
for source in sources:
(base, sext) = os.path.splitext(source)
if sext == ".i": # SWIG interface file
if os.path.split(base)[1] in swig_include_files:
continue
swig_sources.append(source)
# Patch up the filenames for various special cases...
if os.path.basename(base) in swig_interface_parents:
swig_targets[source] = base + target_ext
else:
new_target = f"{base}_swig{target_ext}"
new_sources.append(new_target)
swig_targets[source] = new_target
else:
new_sources.append(source)
if not swig_sources:
return new_sources
swig = self.find_swig()
for source in swig_sources:
swig_cmd = [
swig,
"-python",
"-c++",
# we never use the .doc files.
"-dnone",
]
swig_cmd.extend(self.current_extension.extra_swig_commands)
if platform.machine() in ("AMD64", "ARM64"):
swig_cmd.append("-DSWIG_PY64BIT")
else:
swig_cmd.append("-DSWIG_PY32BIT")
target = swig_targets[source]
interface_parent = swig_interface_parents.get(
os.path.basename(os.path.splitext(source)[0]),
None, # "normal" swig file - no special win32 issues.
)
# Using win32 extensions to SWIG for generating COM classes.
if interface_parent is not None:
# generating a class, not a module.
swig_cmd.append("-pythoncom")
if interface_parent:
# A class deriving from other than the default
swig_cmd.extend(["-com_interface_parent", interface_parent])
# This 'newer' check helps Python 2.2 builds, which otherwise
# *always* regenerate the .cpp files, meaning every future
# build for any platform sees these as dirty.
# This could probably go once we generate .cpp into the temp dir.
fqsource = os.path.abspath(source)
fqtarget = os.path.abspath(target)
rebuild = self.force or (
ext and newer_group(ext.swig_deps + [fqsource], fqtarget)
)
# can remove once edklib is no longer used for 32-bit builds
if source == "com/win32comext/mapi/src/exchange.i":
rebuild = True
logging.debug("should swig %s->%s=%s", source, target, rebuild)
if rebuild:
swig_cmd.extend(["-o", fqtarget, fqsource])
logging.info("swigging %s to %s", source, target)
out_dir = os.path.dirname(source)
cwd = os.getcwd()
os.chdir(out_dir)
try:
self.spawn(swig_cmd)
finally:
os.chdir(cwd)
else:
logging.info("skipping swig of %s", source)
return new_sources
class my_install(install):
def run(self):
install.run(self)
# Custom script we run at the end of installing - this is the same script
# run by bdist_wininst
# If self.root has a value, it means we are being "installed" into
# some other directory than Python itself (eg, into a temp directory
# for bdist_wininst to use) - in which case we must *not* run our
# installer
if not self.dry_run and not self.root:
# We must run the script we just installed into Scripts, as it
# may have had 2to3 run over it.
filename = os.path.join(self.install_scripts, "pywin32_postinstall.py")
if not os.path.isfile(filename):
raise RuntimeError(f"Can't find '{filename}'")
print("Executing post install script...")
# As of setuptools>=74.0.0, we no longer need to
# be concerned about distutils calling win32api
subprocess.Popen(
[
sys.executable,
filename,
"-install",
"-destination",
self.install_lib,
"-quiet",
"-wait",
str(os.getpid()),
]
)
class my_install_lib(install_lib):
def install(self):
# This is crazy - in setuptools 61.1.0 (and probably some earlier versions), the
# install_lib and build comments don't agree on where the .py files to install can
# be found, so we end up with a warning logged:
# `warning: my_install_lib: 'build\lib.win-amd64-3.8' does not exist -- no Python modules to install`
# (because they are actually in `build\lib.win-amd64-cpython-38`!)
# It's not an error though, so we end up with .exe installers lacking our lib files!
builder = self.get_finalized_command("build")
if os.path.isdir(builder.build_platlib) and not os.path.isdir(self.build_dir):
self.build_dir = builder.build_platlib
# We want a failure to find .py files be an error rather than a warning.
outfiles = super().install()
if not outfiles:
raise RuntimeError("No Python files were found to install")
return outfiles
def my_new_compiler(**kw):
if "compiler" in kw and kw["compiler"] in (None, "msvc"):
return my_compiler()
return orig_new_compiler(**kw)
# No way to cleanly wedge our compiler sub-class in.
orig_new_compiler = ccompiler.new_compiler
ccompiler.new_compiler = my_new_compiler # type: ignore[assignment] # Assuming the caller will always use only kwargs
class my_compiler(MSVCCompiler):
# Just one GUIDS.CPP and it gives trouble on mainwin too. Maybe I
# should just rename the file, but a case-only rename is likely to be
# worse! This can probably go away once we kill the VS project files
# though, as we can just specify the lowercase name in the module def.
_cpp_extensions = MSVCCompiler._cpp_extensions + [".CPP"]
src_extensions = MSVCCompiler.src_extensions + [".CPP"]
def link(
self,
target_desc,
objects,
output_filename,
output_dir=None,
libraries=None,
library_dirs=None,
runtime_library_dirs=None,
export_symbols=None,
debug=0,
*args,
**kw,
):
super().link(
target_desc,
objects,
output_filename,
output_dir,
libraries,
library_dirs,
runtime_library_dirs,
export_symbols,
debug,
*args,
**kw,
)
# Here seems a good place to stamp the version of the built
# target. Do this externally to avoid suddenly dragging in the
# modules needed by this process, and which we will soon try and
# update.
args = [
sys.executable,
# NOTE: On Python 3.7, all args must be str
str(Path(__file__).parent / "win32" / "Lib" / "win32verstamp.py"),
f"--version={pywin32_version}",
"--comments=https://github.com/mhammond/pywin32",
f"--original-filename={os.path.basename(output_filename)}",
"--product=PyWin32",
"--quiet" if "-v" not in sys.argv else "",
output_filename,
]
self.spawn(args)
# Work around bpo-36302/bpo-42009 - it sorts sources but this breaks
# support for building .mc files etc :(
def compile(self, sources, **kwargs):
# re-sort the list of source files but ensure all .mc files come first.
def key_reverse_mc(a):
b, e = os.path.splitext(a)
e = "" if e == ".mc" else e
return (e, b)
sources = sorted(sources, key=key_reverse_mc)
return MSVCCompiler.compile(self, sources, **kwargs)
def spawn(self, cmd):
is_link = cmd[0].endswith("link.exe") or cmd[0].endswith('"link.exe"')
is_mt = cmd[0].endswith("mt.exe") or cmd[0].endswith('"mt.exe"')
if is_mt:
# We don't want mt.exe run...
return
if is_link:
# remove /MANIFESTFILE:... and add MANIFEST:NO
for i in range(len(cmd)):
if cmd[i].startswith(("/MANIFESTFILE:", "/MANIFEST:EMBED")):
cmd[i] = "/MANIFEST:NO"
break
if is_mt:
# We want mt.exe run with the original manifest