-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdistutils_buildexe.py
1749 lines (1526 loc) · 74 KB
/
distutils_buildexe.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
import sys
import warnings
from distutils.core import Command
## from distutils.spawn import spawn
## from distutils.errors import *
## import sys, os, imp, types, stat
## import marshal
## import zipfile
## try:
## set
## except NameError:
## from sets import Set as set
## import tempfile
## import struct
## import re
## import fnmatch
## is_win64 = struct.calcsize("P") == 8
## def _is_debug_build():
## for ext, _, _ in imp.get_suffixes():
## if ext == "_d.pyd":
## return True
## return False
## is_debug_build = _is_debug_build()
## if is_debug_build:
## python_dll = "python%d%d_d.dll" % sys.version_info[:2]
## else:
## python_dll = "python%d%d.dll" % sys.version_info[:2]
## # resource constants
## RT_BITMAP=2
## RT_MANIFEST=24
## # Pattern for modifying the 'requestedExecutionLevel' in the manifest. Groups
## # are setup so all text *except* for the values is matched.
## pat_manifest_uac = re.compile(r'(^.*<requestedExecutionLevel level=")([^"])*(" uiAccess=")([^"])*(".*$)')
## # note: we cannot use the list from imp.get_suffixes() because we want
## # .pyc and .pyo, independent of the optimize flag.
## _py_suffixes = ['.py', '.pyo', '.pyc', '.pyw']
## _c_suffixes = [_triple[0] for _triple in imp.get_suffixes()
## if _triple[2] == imp.C_EXTENSION]
## def imp_find_module(name):
## # same as imp.find_module, but handles dotted names
## names = name.split('.')
## path = None
## for name in names:
## result = imp.find_module(name, path)
## path = [result[1]]
## return result
def fancy_split(str, sep=","):
# a split which also strips whitespace from the items
# passing a list or tuple will return it unchanged
if str is None:
return []
if hasattr(str, "split"):
return [item.strip() for item in str.split(sep)]
return str
## def ensure_unicode(text):
## if isinstance(text, unicode):
## return text
## return text.decode("mbcs")
## # This loader locates extension modules relative to the library.zip
## # file when an archive is used (i.e., skip_archive is not used), otherwise
## # it locates extension modules relative to sys.prefix.
## LOADER = """
## def __load():
## import imp, os, sys
## try:
## dirname = os.path.dirname(__loader__.archive)
## except NameError:
## dirname = sys.prefix
## path = os.path.join(dirname, '%s')
## #print "py2exe extension module", __name__, "->", path
## mod = imp.load_dynamic(__name__, path)
## ## mod.frozen = 1
## __load()
## del __load
## """
from . import runtime
class py2exe(Command):
description = ""
# List of option tuples: long name, short name (None if no short
# name), and help string.
user_options = [
('optimize=', 'O',
"optimization level: -O1 for \"python -O\", "
"-O2 for \"python -OO\", and -O0 to disable [default: -O0]"),
('exeoptimize=', None,
"optimization level for executable [default: same as optimize]"),
('dist-dir=', 'd',
"directory to put final built distributions in (default is dist)"),
("excludes=", 'e',
"comma-separated list of modules to exclude"),
("dll-excludes=", None,
"comma-separated list of DLLs to exclude"),
("ignores=", None,
"comma-separated list of modules to ignore if they are not found"),
("includes=", 'i',
"comma-separated list of modules to include"),
("packages=", 'p',
"comma-separated list of packages to include"),
("compressed", 'c',
"create a compressed zipfile"),
("xref", 'x',
"create and show a module cross reference"),
("bundle-files=", 'b',
"bundle dlls in the zipfile or the exe. Valid levels are 1, 2, or 3 (default)"),
("skip-archive", None,
"do not place Python bytecode files in an archive, put them directly in the file system"),
("ascii", 'a',
"do not automatically include encodings and codecs"),
('custom-boot-script=', None,
"Python file that will be run when setting up the runtime environment"),
]
boolean_options = ["compressed", "xref", "ascii", "skip-archive"]
def initialize_options (self):
self.xref =0
self.compressed = 0
self.unbuffered = 0
self.optimize = 0
self.exeoptimize = -1
self.includes = None
self.excludes = None
self.ignores = None
self.packages = None
self.dist_dir = None
self.dll_excludes = None
self.typelibs = None
self.bundle_files = 3
self.skip_archive = 0
self.ascii = 0
self.custom_boot_script = None
def finalize_options (self):
self.optimize = int(self.optimize)
self.exeoptimize = int(self.exeoptimize)
if self.exeoptimize == -1:
self.exeoptimize = self.optimize
self.excludes = fancy_split(self.excludes)
self.includes = fancy_split(self.includes)
self.ignores = fancy_split(self.ignores)
self.bundle_files = int(self.bundle_files)
if self.bundle_files < 0 or self.bundle_files > 3:
raise ValueError("bundle-files must be 0, 1, 2, or 3, not %s"
% self.bundle_files)
if self.ascii:
warnings.warn("The 'ascii' option is no longer supported, ignored.")
if self.skip_archive:
if self.compressed:
raise ValueError("can't compress when skipping archive")
if self.distribution.zipfile is None:
raise ValueError("zipfile cannot be None when skipping archive")
# includes is stronger than excludes
for m in self.includes:
if m in self.excludes:
self.excludes.remove(m)
self.packages = fancy_split(self.packages)
self.set_undefined_options('bdist',
('dist_dir', 'dist_dir'))
self.dll_excludes = [x.lower() for x in fancy_split(self.dll_excludes)]
def run(self):
build = self.reinitialize_command('build')
build.run()
sys_old_path = sys.path[:]
try:
## if build.build_platlib is not None:
## sys.path.insert(0, build.build_platlib)
## if build.build_lib is not None:
## sys.path.insert(0, build.build_lib)
self._run()
## except Exception:
## import traceback; traceback.print_exc()
# XXX need another way to report (?)
finally:
sys.path = sys_old_path
def _run(self):
dist = self.distribution
## # all of these contain module names
## required_modules = []
## for target in dist.com_server + dist.service + dist.ctypes_com_server:
## required_modules.extend(target.modules)
## required_files = [target.script
## for target in dist.windows + dist.console]
dist.console = runtime.fixup_targets(dist.console, "script")
for target in dist.console:
target.exe_type = "console_exe"
dist.windows = runtime.fixup_targets(dist.windows, "script")
for target in dist.windows:
target.exe_type = "windows_exe"
dist.service = runtime.fixup_targets(dist.service, "modules")
for target in dist.service:
target.exe_type = "service"
dist.ctypes_com_server = runtime.fixup_targets(dist.ctypes_com_server, "modules")
for target in dist.ctypes_com_server:
target.exe_type = "ctypes_comdll"
## # Convert our args into target objects.
## dist.com_server = FixupTargets(dist.com_server, "modules")
## dist.ctypes_com_server = FixupTargets(dist.ctypes_com_server, "modules")
## dist.windows = FixupTargets(dist.windows, "script")
## dist.console = FixupTargets(dist.console, "script")
## dist.isapi = FixupTargets(dist.isapi, "script")
from argparse import Namespace
options = Namespace(xref = self.xref,
comppressed = self.compressed,
unbuffered = self.unbuffered,
optimize = self.optimize,
exeoptimize = self.exeoptimize,
includes = self.includes,
excludes = self.excludes,
ignores = self.ignores,
packages = self.packages,
dist_dist = self.dist_dir,
dll_excludes = self.dll_excludes,
typelibs = self.typelibs,
bundle_files = self.bundle_files,
skip_archive = self.skip_archive,
ascii = self.ascii,
custom_boot_script = self.custom_boot_script,
script = dist.console + dist.windows,
service = dist.service,
com_servers = dist.ctypes_com_server,
destdir = self.dist_dir,
libname = dist.zipfile,
verbose = self.verbose,
report = False,
summary = False,
show_from = None,
data_files = self.distribution.data_files,
compress = self.compressed,
)
## level = logging.INFO if options.verbose else logging.WARNING
## logging.basicConfig(level=level)
builder = runtime.Runtime(options)
builder.analyze()
builder.build()
## self.create_directories()
## self.plat_prepare()
## self.fixup_distribution()
## dist = self.distribution
## # all of these contain module names
## required_modules = []
## for target in dist.com_server + dist.service + dist.ctypes_com_server:
## required_modules.extend(target.modules)
## # and these contains file names
## required_files = [target.script
## for target in dist.windows + dist.console]
## mf = self.create_modulefinder()
## # These are the name of a script, but used as a module!
## for f in dist.isapi:
## mf.load_file(f.script)
## if self.typelibs:
## print "*** generate typelib stubs ***"
## from distutils.dir_util import mkpath
## genpy_temp = os.path.join(self.temp_dir, "win32com", "gen_py")
## mkpath(genpy_temp)
## num_stubs = collect_win32com_genpy(genpy_temp,
## self.typelibs,
## verbose=self.verbose,
## dry_run=self.dry_run)
## print "collected %d stubs from %d type libraries" \
## % (num_stubs, len(self.typelibs))
## mf.load_package("win32com.gen_py", genpy_temp)
## self.packages.append("win32com.gen_py")
## # monkey patching the compile builtin.
## # The idea is to include the filename in the error message
## orig_compile = compile
## import __builtin__
## def my_compile(source, filename, *args):
## try:
## result = orig_compile(source, filename, *args)
## except Exception, details:
## raise DistutilsError("compiling '%s' failed\n %s: %s" % \
## (filename, details.__class__.__name__, details))
## return result
## __builtin__.compile = my_compile
## print "*** searching for required modules ***"
## self.find_needed_modules(mf, required_files, required_modules)
## print "*** parsing results ***"
## py_files, extensions, builtins = self.parse_mf_results(mf)
## if self.xref:
## mf.create_xref()
## print "*** finding dlls needed ***"
## alldlls = self.find_dlls(extensions)
## dlls = set()
## for dll in alldlls:
## for filter in self.dll_excludes:
## if fnmatch.fnmatch(os.path.basename(dll), filter):
## break
## else:
## dlls.add(dll)
## # should we filter self.other_depends in the same way?
## self.plat_finalize(mf.modules, py_files, extensions, dlls)
## print "*** create binaries ***"
## self.create_binaries(py_files, extensions, dlls)
## self.fix_badmodules(mf)
## if mf.any_missing():
## print "The following modules appear to be missing"
## print mf.any_missing()
## if self.other_depends:
## print
## print "*** binary dependencies ***"
## print "Your executable(s) also depend on these dlls which are not included,"
## print "you may or may not need to distribute them."
## print
## print "Make sure you have the license if you distribute any of them, and"
## print "make sure you don't distribute files belonging to the operating system."
## print
## for fnm in self.other_depends:
## print " ", os.path.basename(fnm), "-", fnm.strip()
## def create_modulefinder(self):
## from modulefinder import ReplacePackage
## from py2exe.mf import ModuleFinder
## ReplacePackage("_xmlplus", "xml")
## return ModuleFinder(excludes=self.excludes)
## def fix_badmodules(self, mf):
## # This dictionary maps additional builtin module names to the
## # module that creates them.
## # For example, 'wxPython.misc' creates a builtin module named
## # 'miscc'.
## builtins = {"clip_dndc": "wxPython.clip_dnd",
## "cmndlgsc": "wxPython.cmndlgs",
## "controls2c": "wxPython.controls2",
## "controlsc": "wxPython.controls",
## "eventsc": "wxPython.events",
## "filesysc": "wxPython.filesys",
## "fontsc": "wxPython.fonts",
## "framesc": "wxPython.frames",
## "gdic": "wxPython.gdi",
## "imagec": "wxPython.image",
## "mdic": "wxPython.mdi",
## "misc2c": "wxPython.misc2",
## "miscc": "wxPython.misc",
## "printfwc": "wxPython.printfw",
## "sizersc": "wxPython.sizers",
## "stattoolc": "wxPython.stattool",
## "streamsc": "wxPython.streams",
## "utilsc": "wxPython.utils",
## "windows2c": "wxPython.windows2",
## "windows3c": "wxPython.windows3",
## "windowsc": "wxPython.windows",
## }
## # Somewhat hackish: change modulefinder's badmodules dictionary in place.
## bad = mf.badmodules
## # mf.badmodules is a dictionary mapping unfound module names
## # to another dictionary, the keys of this are the module names
## # importing the unknown module. For the 'miscc' module
## # mentioned above, it looks like this:
## # mf.badmodules["miscc"] = { "wxPython.miscc": 1 }
## for name in mf.any_missing():
## if name in self.ignores:
## del bad[name]
## continue
## mod = builtins.get(name, None)
## if mod is not None:
## if mod in bad[name] and bad[name] == {mod: 1}:
## del bad[name]
## def find_dlls(self, extensions):
## dlls = [item.__file__ for item in extensions]
## ## extra_path = ["."] # XXX
## extra_path = []
## dlls, unfriendly_dlls, other_depends = \
## self.find_dependend_dlls(dlls,
## extra_path + sys.path,
## self.dll_excludes)
## self.other_depends = other_depends
## # dlls contains the path names of all dlls we need.
## # If a dll uses a function PyImport_ImportModule (or what was it?),
## # it's name is additionally in unfriendly_dlls.
## for item in extensions:
## if item.__file__ in dlls:
## dlls.remove(item.__file__)
## return dlls
## def create_directories(self):
## bdist_base = self.get_finalized_command('bdist').bdist_base
## self.bdist_dir = os.path.join(bdist_base, 'winexe')
## collect_name = "collect-%d.%d" % sys.version_info[:2]
## self.collect_dir = os.path.abspath(os.path.join(self.bdist_dir, collect_name))
## self.mkpath(self.collect_dir)
## bundle_name = "bundle-%d.%d" % sys.version_info[:2]
## self.bundle_dir = os.path.abspath(os.path.join(self.bdist_dir, bundle_name))
## self.mkpath(self.bundle_dir)
## self.temp_dir = os.path.abspath(os.path.join(self.bdist_dir, "temp"))
## self.mkpath(self.temp_dir)
## self.dist_dir = os.path.abspath(self.dist_dir)
## self.mkpath(self.dist_dir)
## if self.distribution.zipfile is None:
## self.lib_dir = self.dist_dir
## else:
## self.lib_dir = os.path.join(self.dist_dir,
## os.path.dirname(self.distribution.zipfile))
## self.mkpath(self.lib_dir)
## def copy_extensions(self, extensions):
## print "*** copy extensions ***"
## # copy the extensions to the target directory
## for item in extensions:
## src = item.__file__
## if self.bundle_files > 2: # don't bundle pyds and dlls
## dst = os.path.join(self.lib_dir, (item.__pydfile__))
## self.copy_file(src, dst, preserve_mode=0)
## self.lib_files.append(dst)
## else:
## # we have to preserve the packages
## package = "\\".join(item.__name__.split(".")[:-1])
## if package:
## dst = os.path.join(package, os.path.basename(src))
## else:
## dst = os.path.basename(src)
## self.copy_file(src, os.path.join(self.collect_dir, dst), preserve_mode=0)
## self.compiled_files.append(dst)
## def copy_dlls(self, dlls):
## # copy needed dlls where they belong.
## print "*** copy dlls ***"
## if self.bundle_files < 3:
## self.copy_dlls_bundle_files(dlls)
## return
## # dlls belong into the lib_dir, except those listed in dlls_in_exedir,
## # which have to go into exe_dir (pythonxy.dll, w9xpopen.exe).
## for dll in dlls:
## base = os.path.basename(dll)
## if base.lower() in self.dlls_in_exedir:
## # These special dlls cannot be in the lib directory,
## # they must go into the exe directory.
## dst = os.path.join(self.exe_dir, base)
## else:
## dst = os.path.join(self.lib_dir, base)
## _, copied = self.copy_file(dll, dst, preserve_mode=0)
## if not self.dry_run and copied and base.lower() == python_dll.lower():
## # If we actually copied pythonxy.dll, we have to patch it.
## #
## # Previously, the code did it every time, but this
## # breaks if, for example, someone runs UPX over the
## # dist directory. Patching an UPX'd dll seems to work
## # (no error is detected when patching), but the
## # resulting dll does not work anymore.
## #
## # The function restores the file times so
## # dependencies still work correctly.
## self.patch_python_dll_winver(dst)
## self.lib_files.append(dst)
## def copy_dlls_bundle_files(self, dlls):
## # If dlls have to be bundled, they are copied into the
## # collect_dir and will be added to the list of files to
## # include in the zip archive 'self.compiled_files'.
## #
## # dlls listed in dlls_in_exedir have to be treated differently:
## #
## for dll in dlls:
## base = os.path.basename(dll)
## if base.lower() in self.dlls_in_exedir:
## # pythonXY.dll must be bundled as resource.
## # w9xpopen.exe must be copied to self.exe_dir.
## if base.lower() == python_dll.lower() and self.bundle_files < 2:
## dst = os.path.join(self.bundle_dir, base)
## else:
## dst = os.path.join(self.exe_dir, base)
## _, copied = self.copy_file(dll, dst, preserve_mode=0)
## if not self.dry_run and copied and base.lower() == python_dll.lower():
## # If we actually copied pythonxy.dll, we have to
## # patch it. Well, since it's impossible to load
## # resources from the bundled dlls it probably
## # doesn't matter.
## self.patch_python_dll_winver(dst)
## self.lib_files.append(dst)
## continue
## dst = os.path.join(self.collect_dir, os.path.basename(dll))
## self.copy_file(dll, dst, preserve_mode=0)
## # Make sure they will be included into the zipfile.
## self.compiled_files.append(os.path.basename(dst))
## def create_binaries(self, py_files, extensions, dlls):
## dist = self.distribution
## # byte compile the python modules into the target directory
## print "*** byte compile python files ***"
## self.compiled_files = byte_compile(py_files,
## target_dir=self.collect_dir,
## optimize=self.optimize,
## force=0,
## verbose=self.verbose,
## dry_run=self.dry_run)
## self.lib_files = []
## self.console_exe_files = []
## self.windows_exe_files = []
## self.service_exe_files = []
## self.comserver_files = []
## self.copy_extensions(extensions)
## self.copy_dlls(dlls)
## # create the shared zipfile containing all Python modules
## if dist.zipfile is None:
## fd, archive_name = tempfile.mkstemp()
## os.close(fd)
## else:
## archive_name = os.path.join(self.lib_dir,
## os.path.basename(dist.zipfile))
## arcname = self.make_lib_archive(archive_name,
## base_dir=self.collect_dir,
## files=self.compiled_files,
## verbose=self.verbose,
## dry_run=self.dry_run)
## if dist.zipfile is not None:
## self.lib_files.append(arcname)
## for target in self.distribution.isapi:
## print "*** copy isapi support DLL ***"
## # Locate the support DLL, and copy as "_script.dll", just like
## # isapi itself
## import isapi
## src_name = is_debug_build and "PyISAPI_loader_d.dll" or \
## "PyISAPI_loader.dll"
## src = os.path.join(isapi.__path__[0], src_name)
## # destination name is "_{module_name}.dll" just like pyisapi does.
## script_base = os.path.splitext(os.path.basename(target.script))[0]
## dst = os.path.join(self.exe_dir, "_" + script_base + ".dll")
## self.copy_file(src, dst, preserve_mode=0)
## if self.distribution.has_data_files():
## print "*** copy data files ***"
## install_data = self.reinitialize_command('install_data')
## install_data.install_dir = self.dist_dir
## install_data.ensure_finalized()
## install_data.run()
## self.lib_files.extend(install_data.get_outputs())
## # build the executables
## for target in dist.console:
## dst = self.build_executable(target, self.get_console_template(),
## arcname, target.script)
## self.console_exe_files.append(dst)
## for target in dist.windows:
## dst = self.build_executable(target, self.get_windows_template(),
## arcname, target.script)
## self.windows_exe_files.append(dst)
## for target in dist.service:
## dst = self.build_service(target, self.get_service_template(),
## arcname)
## self.service_exe_files.append(dst)
## for target in dist.isapi:
## dst = self.build_isapi(target, self.get_isapi_template(), arcname)
## for target in dist.com_server:
## if getattr(target, "create_exe", True):
## dst = self.build_comserver(target, self.get_comexe_template(),
## arcname)
## self.comserver_files.append(dst)
## if getattr(target, "create_dll", True):
## dst = self.build_comserver(target, self.get_comdll_template(),
## arcname)
## self.comserver_files.append(dst)
## for target in dist.ctypes_com_server:
## dst = self.build_comserver(target, self.get_ctypes_comdll_template(),
## arcname, boot_script="ctypes_com_server")
## self.comserver_files.append(dst)
## if dist.zipfile is None:
## os.unlink(arcname)
## else:
## if self.bundle_files < 3 or self.compressed:
## arcbytes = open(arcname, "rb").read()
## arcfile = open(arcname, "wb")
## if self.bundle_files < 2: # bundle pythonxy.dll also
## print "Adding %s to %s" % (python_dll, arcname)
## arcfile.write("<pythondll>")
## bytes = open(os.path.join(self.bundle_dir, python_dll), "rb").read()
## arcfile.write(struct.pack("i", len(bytes)))
## arcfile.write(bytes) # python dll
## if self.compressed:
## # prepend zlib.pyd also
## zlib_file = imp.find_module("zlib")[0]
## if zlib_file:
## print "Adding zlib%s.pyd to %s" % (is_debug_build and "_d" or "", arcname)
## arcfile.write("<zlib.pyd>")
## bytes = zlib_file.read()
## arcfile.write(struct.pack("i", len(bytes)))
## arcfile.write(bytes) # zlib.pyd
## arcfile.write(arcbytes)
## #### if self.bundle_files < 2:
## #### # remove python dll from the exe_dir, since it is now bundled.
## #### os.remove(os.path.join(self.exe_dir, python_dll))
## # for user convenience, let subclasses override the templates to use
## def get_console_template(self):
## return is_debug_build and "run_d.exe" or "run.exe"
## def get_windows_template(self):
## return is_debug_build and "run_w_d.exe" or "run_w.exe"
## def get_service_template(self):
## return is_debug_build and "run_d.exe" or "run.exe"
## def get_isapi_template(self):
## return is_debug_build and "run_isapi_d.dll" or "run_isapi.dll"
## def get_comexe_template(self):
## return is_debug_build and "run_w_d.exe" or "run_w.exe"
## def get_comdll_template(self):
## return is_debug_build and "run_dll_d.dll" or "run_dll.dll"
## def get_ctypes_comdll_template(self):
## return is_debug_build and "run_ctypes_dll_d.dll" or "run_ctypes_dll.dll"
## def fixup_distribution(self):
## dist = self.distribution
## # Convert our args into target objects.
## dist.com_server = FixupTargets(dist.com_server, "modules")
## dist.ctypes_com_server = FixupTargets(dist.ctypes_com_server, "modules")
## dist.service = FixupTargets(dist.service, "modules")
## dist.windows = FixupTargets(dist.windows, "script")
## dist.console = FixupTargets(dist.console, "script")
## dist.isapi = FixupTargets(dist.isapi, "script")
## # make sure all targets use the same directory, this is
## # also the directory where the pythonXX.dll must reside
## paths = set()
## for target in dist.com_server + dist.service \
## + dist.windows + dist.console + dist.isapi:
## paths.add(os.path.dirname(target.get_dest_base()))
## if len(paths) > 1:
## raise DistutilsOptionError("all targets must use the same directory: %s" % \
## [p for p in paths])
## if paths:
## exe_dir = paths.pop() # the only element
## if os.path.isabs(exe_dir):
## raise DistutilsOptionError("exe directory must be relative: %s" % exe_dir)
## self.exe_dir = os.path.join(self.dist_dir, exe_dir)
## self.mkpath(self.exe_dir)
## else:
## # Do we allow to specify no targets?
## # We can at least build a zipfile...
## self.exe_dir = self.lib_dir
## def get_boot_script(self, boot_type):
## # return the filename of the script to use for com servers.
## thisfile = sys.modules['py2exe.build_exe'].__file__
## return os.path.join(os.path.dirname(thisfile),
## "boot_" + boot_type + ".py")
## def build_comserver(self, target, template, arcname, boot_script="com_servers"):
## # Build a dll and an exe executable hosting all the com
## # objects listed in module_names.
## # The basename of the dll/exe is the last part of the first module.
## # Do we need a way to specify the name of the files to be built?
## # Setup the variables our boot script needs.
## vars = {"com_module_names" : target.modules}
## boot = self.get_boot_script(boot_script)
## # and build it
## return self.build_executable(target, template, arcname, boot, vars)
## def get_service_names(self, module_name):
## # import the script with every side effect :)
## __import__(module_name)
## mod = sys.modules[module_name]
## for name, klass in mod.__dict__.iteritems():
## if hasattr(klass, "_svc_name_"):
## break
## else:
## raise RuntimeError("No services in module")
## deps = ()
## if hasattr(klass, "_svc_deps_"):
## deps = klass._svc_deps_
## return klass.__name__, klass._svc_name_, klass._svc_display_name_, deps
## def build_service(self, target, template, arcname):
## # It should be possible to host many modules in a single service -
## # but this is yet to be tested.
## assert len(target.modules)==1, "We only support one service module"
## cmdline_style = getattr(target, "cmdline_style", "py2exe")
## if cmdline_style not in ["py2exe", "pywin32", "custom"]:
## raise RuntimeError("cmdline_handler invalid")
## vars = {"service_module_names" : target.modules,
## "cmdline_style": cmdline_style,
## }
## boot = self.get_boot_script("service")
## return self.build_executable(target, template, arcname, boot, vars)
## def build_isapi(self, target, template, arcname):
## target_module = os.path.splitext(os.path.basename(target.script))[0]
## vars = {"isapi_module_name" : target_module,
## }
## return self.build_executable(target, template, arcname, None, vars)
## def build_manifest(self, target, template):
## # Optionally return a manifest to be included in the target executable.
## # Note for Python 2.6 and later, its *necessary* to include a manifest
## # which correctly references the CRT. For earlier versions, a manifest
## # is optional, and only necessary to customize things like
## # Vista's User Access Control 'requestedExecutionLevel' setting, etc.
## default_manifest = """
## <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
## <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
## <security>
## <requestedPrivileges>
## <requestedExecutionLevel level="asInvoker" uiAccess="false"></requestedExecutionLevel>
## </requestedPrivileges>
## </security>
## </trustInfo>
## </assembly>
## """
## from py2exe_util import load_resource
## if os.path.splitext(template)[1]==".exe":
## rid = 1
## else:
## rid = 2
## try:
## # Manfiests have resource type of 24, and ID of either 1 or 2.
## mfest = load_resource(ensure_unicode(template), RT_MANIFEST, rid)
## # we consider the manifest 'changed' as we know we clobber all
## # resources including the existing manifest - so this manifest must
## # get written even if we make no other changes.
## changed = True
## except RuntimeError:
## mfest = default_manifest
## # in this case the template had no existing manifest, so its
## # not considered 'changed' unless we make further changes later.
## changed = False
## # update the manifest according to our options.
## # for now a regex will do.
## if target.uac_info:
## changed = True
## if isinstance(target.uac_info, tuple):
## exec_level, ui = target.uac_info
## else:
## exec_level = target.uac_info
## ui = False
## new_lines = []
## for line in mfest.splitlines():
## repl = r'\1%s\3%s\5' % (exec_level, ui)
## new_lines.append(re.sub(pat_manifest_uac, repl, line))
## mfest = "".join(new_lines)
## if not changed:
## return None, None
## return mfest, rid
## def build_executable(self, target, template, arcname, script, vars={}):
## # Build an executable for the target
## # template is the exe-stub to use, and arcname is the zipfile
## # containing the python modules.
## from py2exe_util import add_resource, add_icon
## ext = os.path.splitext(template)[1]
## exe_base = target.get_dest_base()
## exe_path = os.path.join(self.dist_dir, exe_base + ext)
## # The user may specify a sub-directory for the exe - that's fine, we
## # just specify the parent directory for the .zip
## parent_levels = len(os.path.normpath(exe_base).split(os.sep))-1
## lib_leaf = self.lib_dir[len(self.dist_dir)+1:]
## relative_arcname = ((".." + os.sep) * parent_levels)
## if lib_leaf: relative_arcname += lib_leaf + os.sep
## relative_arcname += os.path.basename(arcname)
## src = os.path.join(os.path.dirname(__file__), template)
## # We want to force the creation of this file, as otherwise distutils
## # will see the earlier time of our 'template' file versus the later
## # time of our modified template file, and consider our old file OK.
## old_force = self.force
## self.force = True
## self.copy_file(src, exe_path, preserve_mode=0)
## self.force = old_force
## # Make sure the file is writeable...
## os.chmod(exe_path, stat.S_IREAD | stat.S_IWRITE)
## try:
## f = open(exe_path, "a+b")
## f.close()
## except IOError, why:
## print "WARNING: File %s could not be opened - %s" % (exe_path, why)
## # We create a list of code objects, and write it as a marshaled
## # stream. The framework code then just exec's these in order.
## # First is our common boot script.
## boot = self.get_boot_script("common")
## boot_code = compile(file(boot, "U").read(),
## os.path.abspath(boot), "exec")
## code_objects = [boot_code]
## if self.bundle_files < 3:
## code_objects.append(
## compile("import zipextimporter; zipextimporter.install()",
## "<install zipextimporter>", "exec"))
## for var_name, var_val in vars.iteritems():
## code_objects.append(
## compile("%s=%r\n" % (var_name, var_val), var_name, "exec")
## )
## if self.custom_boot_script:
## code_object = compile(file(self.custom_boot_script, "U").read() + "\n",
## os.path.abspath(self.custom_boot_script), "exec")
## code_objects.append(code_object)
## if script:
## code_object = compile(open(script, "U").read() + "\n",
## os.path.basename(script), "exec")
## code_objects.append(code_object)
## code_bytes = marshal.dumps(code_objects)
## if self.distribution.zipfile is None:
## relative_arcname = ""
## si = struct.pack("iiii",
## 0x78563412, # a magic value,
## self.optimize,
## self.unbuffered,
## len(code_bytes),
## ) + relative_arcname + "\000"
## script_bytes = si + code_bytes + '\000\000'
## self.announce("add script resource, %d bytes" % len(script_bytes))
## if not self.dry_run:
## add_resource(ensure_unicode(exe_path), script_bytes, u"PYTHONSCRIPT", 1, True)
## # add the pythondll as resource, and delete in self.exe_dir
## if self.bundle_files < 2 and self.distribution.zipfile is None:
## # bundle pythonxy.dll
## dll_path = os.path.join(self.bundle_dir, python_dll)
## bytes = open(dll_path, "rb").read()
## # image, bytes, lpName, lpType
## print "Adding %s as resource to %s" % (python_dll, exe_path)
## add_resource(ensure_unicode(exe_path), bytes,
## # for some reason, the 3. argument MUST BE UPPER CASE,
## # otherwise the resource will not be found.
## ensure_unicode(python_dll).upper(), 1, False)
## if self.compressed and self.bundle_files < 3 and self.distribution.zipfile is None:
## zlib_file = imp.find_module("zlib")[0]
## if zlib_file:
## print "Adding zlib.pyd as resource to %s" % exe_path
## zlib_bytes = zlib_file.read()
## add_resource(ensure_unicode(exe_path), zlib_bytes,
## # for some reason, the 3. argument MUST BE UPPER CASE,
## # otherwise the resource will not be found.
## u"ZLIB.PYD", 1, False)
## # Handle all resources specified by the target
## bitmap_resources = getattr(target, "bitmap_resources", [])
## for bmp_id, bmp_filename in bitmap_resources:
## bmp_data = open(bmp_filename, "rb").read()
## # skip the 14 byte bitmap header.
## if not self.dry_run:
## add_resource(ensure_unicode(exe_path), bmp_data[14:], RT_BITMAP, bmp_id, False)
## icon_resources = getattr(target, "icon_resources", [])
## for ico_id, ico_filename in icon_resources:
## if not self.dry_run:
## add_icon(ensure_unicode(exe_path), ensure_unicode(ico_filename), ico_id)
## # a manifest
## mfest, mfest_id = self.build_manifest(target, src)
## if mfest:
## self.announce("add manifest, %d bytes" % len(mfest))
## if not self.dry_run:
## add_resource(ensure_unicode(exe_path), mfest, RT_MANIFEST, mfest_id, False)
## for res_type, res_id, data in getattr(target, "other_resources", []):
## if not self.dry_run:
## if isinstance(res_type, basestring):
## res_type = ensure_unicode(res_type)
## add_resource(ensure_unicode(exe_path), data, res_type, res_id, False)
## typelib = getattr(target, "typelib", None)
## if typelib is not None:
## data = open(typelib, "rb").read()
## add_resource(ensure_unicode(exe_path), data, u"TYPELIB", 1, False)
## self.add_versioninfo(target, exe_path)
## # Hm, this doesn't make sense with normal executables, which are
## # already small (around 20 kB).
## #
## # But it would make sense with static build pythons, but not
## # if the zipfile is appended to the exe - it will be too slow
## # then (although it is a wonder it works at all in this case).
## #
## # Maybe it would be faster to use the frozen modules machanism
## # instead of the zip-import?
## ## if self.compressed:
## ## import gc
## ## gc.collect() # to close all open files!
## ## os.system("upx -9 %s" % exe_path)
## if self.distribution.zipfile is None:
## zip_data = open(arcname, "rb").read()
## open(exe_path, "a+b").write(zip_data)
## return exe_path
## def add_versioninfo(self, target, exe_path):
## # Try to build and add a versioninfo resource
## def get(name, md = self.distribution.metadata):
## # Try to get an attribute from the target, if not defined
## # there, from the distribution's metadata, or None. Note
## # that only *some* attributes are allowed by distutils on
## # the distribution's metadata: version, description, and
## # name.
## return getattr(target, name, getattr(md, name, None))
## version = get("version")
## if version is None:
## return
## from py2exe.resources.VersionInfo import Version, RT_VERSION, VersionError
## version = Version(version,
## file_description = get("description"),
## comments = get("comments"),
## company_name = get("company_name"),
## legal_copyright = get("copyright"),
## legal_trademarks = get("trademarks"),
## original_filename = os.path.basename(exe_path),
## product_name = get("name"),
## product_version = get("product_version") or version)
## try:
## bytes = version.resource_bytes()
## except VersionError, detail:
## self.warn("Version Info will not be included:\n %s" % detail)
## return
## from py2exe_util import add_resource