forked from winpython/winpython
-
Notifications
You must be signed in to change notification settings - Fork 0
/
make.py
1634 lines (1449 loc) · 56.2 KB
/
make.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
# -*- coding: utf-8 -*-
#
# Copyright © 2012 Pierre Raybaut
# Copyright © 2014-2024+ The Winpython development team https://github.com/winpython/
# Licensed under the terms of the MIT License
# (see winpython/__init__.py for details)
"""
WinPython build script
Created on Sun Aug 12 11:17:50 2012
"""
import os
from pathlib import Path
import re
import subprocess
import shutil
import sys
# Local imports
from winpython import wppm, utils
import diff
CHANGELOGS_DIR = str(Path(__file__).parent / "changelogs")
assert Path(CHANGELOGS_DIR).is_dir()
def get_drives():
"""
This function retrieves a list of existing drives on a Windows system.
Returns:
list: A list of drive letters (e.g., ['C:', 'D:'])
"""
if hasattr(os, 'listdrives'): # For Python 3.12 and above
return os.listdrives()
else:
drives = [f"{d}:\\" for d in os.environ.get('HOMEDRIVE', '').split("\\") if d]
return drives
def get_nsis_exe():
"""Return NSIS executable"""
localdir = str(Path(sys.prefix).parent.parent)
for drive in get_drives():
for dirname in (
r"C:\Program Files",
r"C:\Program Files (x86)",
drive + r"PortableApps\NSISPortableANSI",
drive + r"PortableApps\NSISPortable",
str(Path(localdir) / "NSISPortableANSI"),
str(Path(localdir) / "NSISPortable"),
):
for subdirname in (".", "App"):
exe = str(Path(dirname) / subdirname / "NSIS" / "makensis.exe")
if Path(exe).is_file():
return exe
else:
raise RuntimeError("NSIS is not installed on this computer.")
def get_7zip_exe():
"""Return 7zip executable"""
localdir = str(Path(sys.prefix).parent.parent)
for dirname in (
r"C:\Program Files",
r"C:\Program Files (x86)",
str(Path(localdir) / "7-Zip"),
):
for subdirname in (".", "App"):
exe = str(Path(dirname) / subdirname / "7-Zip" / "7z.exe")
if Path(exe).is_file():
return exe
raise RuntimeError("7ZIP is not installed on this computer.")
def replace_in_nsis_file(fname, data):
"""Replace text in line starting with *start*, from this position:
data is a list of (start, text) tuples"""
fd = open(fname, "U")
lines = fd.readlines()
fd.close()
for idx, line in enumerate(lines):
for start, text in data:
if start not in (
"Icon",
"OutFile",
) and not start.startswith("!"):
start = "!define " + start
if line.startswith(start + " "):
lines[idx] = line[: len(start) + 1] + f'"{text}"' + "\n"
fd = open(fname, "w")
fd.writelines(lines)
print("iss for ", fname, "is", lines)
fd.close()
def replace_in_7zip_file(fname, data):
"""Replace text in line starting with *start*, from this position:
data is a list of (start, text) tuples"""
fd = open(fname, "U")
lines = fd.readlines()
fd.close()
for idx, line in enumerate(lines):
for start, text in data:
if start not in (
"Icon",
"OutFile",
) and not start.startswith("!"):
start = "set " + start
if line.startswith(start + "="):
lines[idx] = line[: len(start) + 1] + f"{text}" + "\n"
fd = open(fname, "w")
fd.writelines(lines)
print("7-zip for ", fname, "is", lines)
fd.close()
def build_shimmy_launcher(launcher_name, command, icon_path, mkshim_program='mkshim400.py', workdir=''):
"""Build .exe launcher with mkshim_program and pywin32"""
# define where is mkshim
mkshim_program = str(Path(__file__).resolve().parent / mkshim_program)
python_program = utils.get_python_executable()
# Create the executable using mkshim.py or mkshim240.py
mkshim_command = f'{python_program} "{mkshim_program}" -f "{launcher_name}" -c "{command}"'
if workdir !='': # V03 of shim: we can handle an optional sub-directory
mkshim_command += f' --subdir "{workdir}"'
# Embed the icon, if provided
if Path(icon_path).is_file():
mkshim_command += f' --i "{icon_path}"'
print(f"Building .exe launcher with {mkshim_program}:", mkshim_command)
subprocess.run(mkshim_command, shell=True)
def build_nsis(srcname, dstname, data):
"""Build NSIS script"""
NSIS_EXE = get_nsis_exe() # NSIS Compiler
portable_dir = str(Path(__file__).resolve().parent / "portable")
shutil.copy(str(Path(portable_dir) / srcname), dstname)
data = [
(
"!addincludedir",
str(Path(portable_dir) / "include"),
)
] + list(data)
replace_in_nsis_file(dstname, data)
try:
retcode = subprocess.call(
f'"{NSIS_EXE}" -V2 "{dstname}"',
shell=True,
stdout=sys.stderr,
)
if retcode < 0:
print(
"Child was terminated by signal",
-retcode,
file=sys.stderr,
)
except OSError as e:
print("Execution failed:", e, file=sys.stderr)
os.remove(dstname)
def build_7zip(srcname, dstname, data):
"""7-Zip Setup Script"""
SEVENZIP_EXE = get_7zip_exe()
portable_dir = str(Path(__file__).resolve().parent / "portable")
shutil.copy(str(Path(portable_dir) / srcname), dstname)
data = [
("PORTABLE_DIR", portable_dir),
("SEVENZIP_EXE", SEVENZIP_EXE),
] + list(data)
replace_in_7zip_file(dstname, data)
try:
# insted of a 7zip command line, we launch a script that does it
# retcode = subprocess.call(f'"{SEVENZIP_EXE}" "{dstname}"'),
retcode = subprocess.call(
f'"{dstname}" ',
shell=True,
stdout=sys.stderr,
)
if retcode < 0:
print(
"Child was terminated by signal",
-retcode,
file=sys.stderr,
)
except OSError as e:
print("Execution failed:", e, file=sys.stderr)
# os.remove(dstname)
class WinPythonDistribution(object):
"""WinPython distribution"""
JULIA_PATH = r"\t\Julia\bin"
NODEJS_PATH = r"\n" # r'\t\n'
def __init__(
self,
build_number,
release_level,
target,
wheeldir,
toolsdirs=None,
verbose=False,
simulation=False,
basedir=None,
install_options=None,
flavor="",
docsdirs=None,
):
assert isinstance(build_number, int)
assert isinstance(release_level, str)
self.build_number = build_number
self.release_level = release_level
self.target = target
self.wheeldir = wheeldir
if toolsdirs is None:
toolsdirs = []
self._toolsdirs = toolsdirs
if docsdirs is None:
docsdirs = []
self._docsdirs = docsdirs
self.verbose = verbose
self.winpydir = None # new WinPython BaseDirectory
self.distribution = None
self.installed_packages = []
self.simulation = simulation
self.basedir = basedir # added to build from winpython
self.install_options = install_options
self.flavor = flavor
# python_fname = the .zip of the python interpreter PyPy !
try: # PyPy
self.python_fname = self.get_package_fname(
r"(pypy3|python-)([0-9]|[a-zA-Z]|.)*.zip"
)
except: # normal Python
self.python_fname = self.get_package_fname(
r"python-([0-9\.rcba]*)((\.|\-)amd64)?\.(zip|zip)"
)
self.python_name = Path(self.python_fname).name[:-4]
self.python_namedir ="python"
@property
def package_index_wiki(self):
"""Return Package Index page in Wiki format"""
installed_tools = []
def get_tool_path_file(relpath):
if self.simulation:
for dirname in self.toolsdirs:
path = dirname + relpath.replace(r"\t", "")
if Path(path).is_file():
return path
else:
path = self.winpydir + relpath
if Path(path).is_file():
return path
def get_tool_path_dir(relpath):
if self.simulation:
for dirname in self.toolsdirs:
path = dirname + relpath.replace(r"\t", "")
if Path(path).is_dir():
return path
else:
path = self.winpydir + relpath
if Path(path).is_dir():
return path
juliapath = get_tool_path_dir(self.JULIA_PATH)
if juliapath is not None:
juliaver = utils.get_julia_version(juliapath)
installed_tools += [("Julia", juliaver)]
nodepath = get_tool_path_dir(self.NODEJS_PATH)
if nodepath is not None:
nodever = utils.get_nodejs_version(nodepath)
installed_tools += [("Nodejs", nodever)]
npmver = utils.get_npmjs_version(nodepath)
installed_tools += [("npmjs", npmver)]
pandocexe = get_tool_path_file(r"\t\pandoc.exe")
if pandocexe is not None:
pandocver = utils.get_pandoc_version(str(Path(pandocexe).parent))
installed_tools += [("Pandoc", pandocver)]
vscodeexe = get_tool_path_file(r"\t\VSCode\Code.exe")
if vscodeexe is not None:
installed_tools += [
("VSCode", utils.getFileProperties(vscodeexe)["FileVersion"])
]
tools = []
for name, ver in installed_tools:
metadata = utils.get_package_metadata("tools.ini", name)
url, desc = (
metadata["url"],
metadata["description"],
)
tools += [f"[{name}]({url}) | {ver} | {desc}"]
# get all packages installed in the changelog, whatever the method
self.installed_packages = self.distribution.get_installed_packages(update=True)
packages = [
f"[{pack.name}]({pack.url}) | {pack.version} | {pack.description}"
for pack in sorted(
self.installed_packages,
key=lambda p: p.name.lower(),
)
]
python_desc = "Python programming language with standard library"
tools_f = "\n".join(tools)
packages_f = "\n".join(packages)
return (
f"""## WinPython {self.winpyver2 + self.flavor}
The following packages are included in WinPython-{self.winpy_arch}bit v{self.winpyver2+self.flavor} {self.release_level}.
<details>
### Tools
Name | Version | Description
-----|---------|------------
{tools_f}
### Python packages
Name | Version | Description
-----|---------|------------
[Python](http://www.python.org/) | {self.python_fullversion} | {python_desc}
{packages_f}"""
+ "\n\n</details>\n"
)
# @property makes self.winpyver becomes a call to self.winpyver()
@property
def winpyver(self):
"""Return WinPython version (with flavor and release level!)"""
return f"{self.python_fullversion}.{self.build_number}{self.flavor}{self.release_level}"
@property
def python_dir(self):
"""Return Python dirname (full path) of the target distribution"""
if (Path(self.winpydir) / self.python_namedir).is_dir(): # 2024-12-22
return str(Path(self.winpydir) / self.python_namedir) # /python path
else:
return str(Path(self.winpydir) / self.python_name) # python.exe path
@property
def winpy_arch(self):
"""Return WinPython architecture"""
return f"{self.distribution.architecture}"
@property
def py_arch(self):
"""Return distribution architecture, in Python distutils format:
win-amd64 or win32"""
if self.distribution.architecture == 64:
return "win-amd64"
else:
return "win32"
@property
def prepath(self):
"""Return PATH contents to be prepend to the environment variable"""
path = [
r"Lib\site-packages\PyQt5",
"", # Python root directory
"DLLs",
"Scripts",
r"..\t",
]
path += [r".." + self.JULIA_PATH]
path += [r".." + self.NODEJS_PATH]
return path
@property
def postpath(self):
"""Return PATH contents to be append to the environment variable"""
path = []
return path
@property
def toolsdirs(self):
"""Return tools directory list"""
# formerly was joining prepared tool dir + the one of building env..
return [] + self._toolsdirs
@property
def docsdirs(self):
"""Return docs directory list"""
if (Path(__file__).resolve().parent / "docs").is_dir():
return [str(Path(__file__).resolve().parent / "docs")] + self._docsdirs
else:
return self._docsdirs
def get_package_fname(self, pattern):
"""Get package matching pattern in wheeldir"""
path = self.wheeldir
for fname in os.listdir(path):
match = re.match(pattern, fname)
if match is not None or pattern == fname:
return str((Path(path) / fname).resolve())
else:
raise RuntimeError(f"Could not find required package matching {pattern}")
def create_batch_script(self, name, contents, do_changes=None):
"""Create batch script %WINPYDIR%/name"""
scriptdir = str(Path(self.winpydir) / "scripts")
if not Path(scriptdir).is_dir():
os.mkdir(scriptdir)
print("dochanges for %s %", name, do_changes)
# live patch pypy3
contents_final = contents
if do_changes != None:
for i in do_changes:
contents_final = contents_final.replace(i[0], i[1])
fd = open(str(Path(scriptdir) / name), "w")
fd.write(contents_final)
fd.close()
def create_launcher_shimmy(
self,
name,
icon,
command=None,
args=None,
workdir=r"", # ".\script" to go to sub-directory of the icon
mkshim_program="mkshim400.py", # to force another one
):
"""Create an exe launcher with mkshim.py"""
assert name.endswith(".exe")
portable_dir = str(Path(__file__).resolve().parent / "portable")
icon_fname = str(Path(portable_dir) / "icons" / icon)
assert Path(icon_fname).is_file()
# prepare mkshim.py script
# $env:WINPYDIRICONS variable give the icons directory
if command is None:
if args is not None and ".pyw" in args:
command = "${WINPYDIR}\pythonw.exe" #not used
else:
command = "${WINPYDIR}\python.exe" #not used
iconlauncherfullname= str(Path(self.winpydir) / name)
true_command = command.replace(r"$SYSDIR\cmd.exe","cmd.exe")+ " " + args
# build_shimmy_launcher(iconlauncherfullname, true_command, icon_fname, mkshim_program=mkshim_program, workdir=workdir)
def create_launcher(
self,
name,
icon,
command=None,
args=None,
workdir=r"$EXEDIR\scripts",
launcher="launcher_basic.nsi",
):
"""Create exe launcher with NSIS"""
assert name.endswith(".exe")
portable_dir = str(Path(__file__).resolve().parent / "portable")
icon_fname = str(Path(portable_dir) / "icons" / icon)
assert Path(icon_fname).is_file()
# Customizing NSIS script
if command is None:
if args is not None and ".pyw" in args:
command = "${WINPYDIR}\pythonw.exe"
else:
command = "${WINPYDIR}\python.exe"
if args is None:
args = ""
if workdir is None:
workdir = ""
fname = str(Path(self.winpydir) / (Path(name).stem + ".nsi"))
data = [
("WINPYDIR", f"$EXEDIR\{self.python_namedir}"), #2024-12-22
("WINPYVER", self.winpyver),
("COMMAND", command),
("PARAMETERS", args),
("WORKDIR", workdir),
("Icon", icon_fname),
("OutFile", name),
]
build_nsis(launcher, fname, data)
def create_python_batch(
self,
name,
script_name,
workdir=None,
options=None,
command=None,
):
"""Create batch file to run a Python script"""
if options is None:
options = ""
else:
options = " " + options
if command is None:
if script_name.endswith(".pyw"):
command = 'start "%WINPYDIR%\pythonw.exe"'
else:
command = '"%WINPYDIR%\python.exe"'
changedir = ""
if workdir is not None:
workdir = workdir
changedir = (
r"""cd/D %s
"""
% workdir
)
if script_name != "":
script_name = " " + script_name
self.create_batch_script(
name,
r"""@echo off
call "%~dp0env_for_icons.bat"
"""
+ changedir
+ command
+ script_name
+ options
+ " %*",
)
def create_installer_7zip(self, installer_option=""):
"""Create installer with 7-ZIP"""
self._print("Creating WinPython installer 7-ZIP")
portable_dir = str(Path(__file__).resolve().parent / "portable")
fname = str(Path(portable_dir) / "installer_7zip-tmp.bat")
data = (
("DISTDIR", self.winpydir),
("ARCH", self.winpy_arch),
(
"VERSION",
f"{self.python_fullversion}.{self.build_number}{self.flavor}",
),
(
"VERSION_INSTALL",
f'{self.python_fullversion.replace(".", "")}' + f"{self.build_number}",
),
("RELEASELEVEL", self.release_level),
)
data += (("INSTALLER_OPTION", installer_option),)
build_7zip("installer_7zip.bat", fname, data)
self._print_done()
def _print(self, text):
"""Print action text indicating progress"""
if self.verbose:
utils.print_box(text)
else:
print(text + "...", end=" ")
def _print_done(self):
"""Print OK at the end of a process"""
if not self.verbose:
print("OK")
def _extract_python(self):
"""Extracting Python installer, creating distribution object"""
self._print("Extracting Python .zip version")
utils.extract_archive(
self.python_fname,
targetdir=self.python_dir + r"\..",
)
self._print_done()
# relocate to /python
if Path(self.python_namedir) != Path(self.winpydir) / self.python_namedir: #2024-12-22 to /python
os.rename(Path(self.python_dir), Path(self.winpydir) / self.python_namedir)
def _copy_dev_tools(self):
"""Copy dev tools"""
self._print(f"Copying tools from {self.toolsdirs} to {self.winpydir}/t")
toolsdir = str(Path(self.winpydir) / "t")
os.mkdir(toolsdir)
for dirname in [
ok_dir for ok_dir in self.toolsdirs if Path(ok_dir).is_dir()
]: # the ones in the make.py script environment
for name in os.listdir(dirname):
path = str(Path(dirname) / name)
copy = shutil.copytree if Path(path).is_dir() else shutil.copyfile
if self.verbose:
print(path + " --> " + str(Path(toolsdir) / name))
copy(path, str(Path(toolsdir) / name))
self._print_done()
# move node higher
nodejs_current = str(Path(toolsdir) / "n")
nodejs_target = self.winpydir + self.NODEJS_PATH
if nodejs_current != nodejs_target and Path(nodejs_current).is_dir():
shutil.move(nodejs_current, nodejs_target)
def _copy_dev_docs(self):
"""Copy dev docs"""
docsdir = str(Path(self.winpydir) / "notebooks")
self._print(f"Copying Noteebook docs from {self.docsdirs} to {docsdir}")
if not Path(docsdir).is_dir():
os.mkdir(docsdir)
docsdir = str(Path(self.winpydir) / "notebooks" / "docs")
if not Path(docsdir).is_dir():
os.mkdir(docsdir)
for dirname in self.docsdirs:
for name in os.listdir(dirname):
path = str(Path(dirname) / name)
copy = shutil.copytree if Path(path).is_dir() else shutil.copyfile
copy(path, str(Path(docsdir) / name))
if self.verbose:
print(path + " --> " + str(Path(docsdir) / name))
self._print_done()
def _create_launchers(self):
"""Create launchers"""
self._print("Creating launchers")
self.create_launcher(
"WinPython Command Prompt.exe",
"cmd.ico",
command="$SYSDIR\cmd.exe",
args=r"/k cmd.bat",
)
#self.create_launcher_shimmy(
# "WinPython Powershell Prompt.exe",
# "powershell.ico",
# command="Powershell.exe",
# args=r"start-process -WindowStyle Hidden -FilePath ([dollar]ENV:WINPYDIRICONS + '\scripts\cmd_ps.bat')",
#)
self.create_launcher(
"WinPython Powershell Prompt.exe",
"powershell.ico",
command="wscript.exe",
args=r"Noshell.vbs cmd_ps.bat",
)
self.create_launcher(
"WinPython Interpreter.exe",
"python.ico",
command="$SYSDIR\cmd.exe",
args=r"/k winpython.bat",
)
self.create_launcher(
"IDLE (Python GUI).exe",
"python.ico",
command="wscript.exe",
args=r"Noshell.vbs winidle.bat",
)
self.create_launcher(
"Spyder.exe",
"spyder.ico",
command="wscript.exe",
args=r"Noshell.vbs winspyder.bat",
)
self.create_launcher(
"Spyder reset.exe",
"spyder_reset.ico",
command="wscript.exe",
args=r"Noshell.vbs spyder_reset.bat",
)
self.create_launcher(
"WinPython Control Panel.exe",
"winpython.ico",
command="$SYSDIR\cmd.exe",
args=r"/k wpcp.bat",
)
# Jupyter launchers
self.create_launcher(
"Jupyter Notebook.exe",
"jupyter.ico",
command="$SYSDIR\cmd.exe",
args=r"/k winipython_notebook.bat", # like VSCode + Rise way
# args=r'/k winjupyter_nbclassic.bat', # Jupyterlab in classic look
)
self.create_launcher(
"Jupyter Lab.exe",
"jupyter.ico",
command="$SYSDIR\cmd.exe",
args=r"/k winjupyter_lab.bat",
)
# VSCode launcher
self.create_launcher(
"VS Code.exe",
"code.ico",
command="wscript.exe",
args=r"Noshell.vbs winvscode.bat",
)
self._print_done()
def _create_batch_scripts_initial(self):
"""Create batch scripts"""
self._print("Creating batch scripts initial")
conv = lambda path: ";".join(["%WINPYDIR%\\" + pth for pth in path])
path = conv(self.prepath) + ";%PATH%;" + conv(self.postpath)
convps = lambda path: ";".join(["$env:WINPYDIR\\" + pth for pth in path])
pathps = convps(self.prepath) + ";$env:path;" + convps(self.postpath)
# PyPy3
shorty = self.distribution.short_exe
changes = (
(r"DIR%\python.exe", r"DIR%" + "\\" + shorty),
(r"DIR%\PYTHON.EXE", r"DIR%" + "\\" + shorty),
)
if (Path(self.distribution.target) / r"lib-python\3\idlelib").is_dir():
changes += ((r"\Lib\idlelib", r"\lib-python\3\idlelib"),)
self.create_batch_script(
"env.bat",
r"""@echo off
set WINPYDIRBASE=%~dp0..
rem set PYTHONUTF8=1 would create issues in "movable" patching
rem get a normalize path
set WINPYDIRBASETMP=%~dp0..
pushd %WINPYDIRBASETMP%
set WINPYDIRBASE=%__CD__%
if "%WINPYDIRBASE:~-1%"=="\" set WINPYDIRBASE=%WINPYDIRBASE:~0,-1%
set WINPYDIRBASETMP=
popd
set WINPYDIR=%WINPYDIRBASE%"""
+ "\\"
+ self.python_namedir
+ r"""
rem 2019-08-25 pyjulia needs absolutely a variable PYTHON=%WINPYDIR%python.exe
set PYTHON=%WINPYDIR%\python.exe
set PYTHONPATHz=%WINPYDIR%;%WINPYDIR%\Lib;%WINPYDIR%\DLLs
set WINPYVER="""
+ self.winpyver
+ r"""
rem 2023-02-12 try utf-8 on console
rem see https://github.com/pypa/pip/issues/11798#issuecomment-1427069681
set PYTHONIOENCODING=utf-8
set HOME=%WINPYDIRBASE%\settings
rem read https://github.com/winpython/winpython/issues/839
rem set USERPROFILE=%HOME%
rem set WINPYDIRBASE=
set JUPYTER_DATA_DIR=%HOME%
set JUPYTER_CONFIG_DIR=%WINPYDIR%\etc\jupyter
set JUPYTER_CONFIG_PATH=%WINPYDIR%\etc\jupyter
set WINPYARCH=WIN32
if "%WINPYDIR:~-5%"=="amd64" set WINPYARCH=WIN-AMD64
set FINDDIR=%WINDIR%\system32
echo ";%PATH%;" | %FINDDIR%\find.exe /C /I ";%WINPYDIR%\;" >nul
if %ERRORLEVEL% NEQ 0 (
set "PATH="""
+ path
+ r""""
cd .
)
rem force default pyqt5 kit for Spyder if PyQt5 module is there
if exist "%WINPYDIR%\Lib\site-packages\PyQt5\__init__.py" set QT_API=pyqt5
""",
do_changes=changes,
)
self.create_batch_script(
"WinPython_PS_Prompt.ps1",
r"""
### WinPython_PS_Prompt.ps1 ###
$0 = $myInvocation.MyCommand.Definition
$dp0 = [System.IO.Path]::GetDirectoryName($0)
# $env:PYTHONUTF8 = 1 would create issues in "movable" patching
$env:WINPYDIRBASE = "$dp0\.."
# get a normalize path
# http://stackoverflow.com/questions/1645843/resolve-absolute-path-from-relative-path-and-or-file-name
$env:WINPYDIRBASE = [System.IO.Path]::GetFullPath( $env:WINPYDIRBASE )
# avoid double_init (will only resize screen)
if (-not ($env:WINPYDIR -eq [System.IO.Path]::GetFullPath( $env:WINPYDIRBASE+"""
+ '"\\'
+ self.python_namedir
+ '"'
+ r""")) ) {
$env:WINPYDIR = $env:WINPYDIRBASE+"""
+ '"'
+ "\\"
+ self.python_namedir
+ '"'
+ r"""
# 2019-08-25 pyjulia needs absolutely a variable PYTHON=%WINPYDIR%python.exe
$env:PYTHON = "%WINPYDIR%\python.exe"
$env:PYTHONPATHz = "%WINPYDIR%;%WINPYDIR%\Lib;%WINPYDIR%\DLLs"
$env:WINPYVER = '"""
+ self.winpyver
+ r"""'
# rem 2023-02-12 try utf-8 on console
# rem see https://github.com/pypa/pip/issues/11798#issuecomment-1427069681
$env:PYTHONIOENCODING = "utf-8"
$env:HOME = "$env:WINPYDIRBASE\settings"
# rem read https://github.com/winpython/winpython/issues/839
# $env:USERPROFILE = "$env:HOME"
$env:WINPYDIRBASE = ""
$env:JUPYTER_DATA_DIR = "$env:HOME"
$env:WINPYARCH = 'WIN32'
if ($env:WINPYARCH.subString($env:WINPYARCH.length-5, 5) -eq 'amd64') {
$env:WINPYARCH = 'WIN-AMD64' }
if (-not $env:PATH.ToLower().Contains(";"+ $env:WINPYDIR.ToLower()+ ";")) {
$env:PATH = """
+ '"'
+ pathps
+ '"'
+ r""" }
#rem force default pyqt5 kit for Spyder if PyQt5 module is there
if (Test-Path "$env:WINPYDIR\Lib\site-packages\PyQt5\__init__.py") { $env:QT_API = "pyqt5" }
# PyQt5 qt.conf creation and winpython.ini creation done via Winpythonini.py (called per env_for_icons.bat for now)
# Start-Process -FilePath $env:PYTHON -ArgumentList ($env:WINPYDIRBASE + '\scripts\WinPythonIni.py')
}
### Set-WindowSize
Function Set-WindowSize {
Param([int]$x=$host.ui.rawui.windowsize.width,
[int]$y=$host.ui.rawui.windowsize.heigth,
[int]$buffer=$host.UI.RawUI.BufferSize.heigth)
$buffersize = new-object System.Management.Automation.Host.Size($x,$buffer)
$host.UI.RawUI.BufferSize = $buffersize
$size = New-Object System.Management.Automation.Host.Size($x,$y)
$host.ui.rawui.WindowSize = $size
}
# Windows10 yelling at us with 150 40 6000
# Set-WindowSize 195 40 6000
### Colorize to distinguish
$host.ui.RawUI.BackgroundColor = "Black"
$host.ui.RawUI.ForegroundColor = "White"
""",
do_changes=changes,
)
self.create_batch_script(
"cmd_ps.bat",
r"""@echo off
call "%~dp0env_for_icons.bat"
Powershell.exe -Command "& {Start-Process PowerShell.exe -ArgumentList '-ExecutionPolicy RemoteSigned -noexit -File ""%~dp0WinPython_PS_Prompt.ps1""'}"
""",
do_changes=changes,
)
self.create_batch_script(
"env_for_icons.bat",
r"""@echo off
call "%~dp0env.bat"
set WINPYWORKDIR=%WINPYDIRBASE%\Notebooks
rem default is as before: Winpython ..\Notebooks
set WINPYWORKDIR1=%WINPYWORKDIR%
rem if we have a file or directory in %1 parameter, we use that directory
if not "%~1"=="" (
if exist "%~1" (
if exist "%~1\" (
rem echo it is a directory %~1
set WINPYWORKDIR1=%~1
) else (
rem echo it is a file %~1, so we take the directory %~dp1
set WINPYWORKDIR1=%~dp1
)
)
) else (
rem if it is launched from another directory than icon origin , we keep it that one echo %__CD__%
if not "%__CD__%"=="%~dp0" if not "%__CD__%scripts\"=="%~dp0" set WINPYWORKDIR1="%__CD__%"
)
rem remove potential doublequote
set WINPYWORKDIR1=%WINPYWORKDIR1:"=%
rem remove some potential last \
if "%WINPYWORKDIR1:~-1%"=="\" set WINPYWORKDIR1=%WINPYWORKDIR1:~0,-1%
FOR /F "delims=" %%i IN ('""%WINPYDIR%\python.exe" "%~dp0WinpythonIni.py""') DO set winpythontoexec=%%i
%winpythontoexec%set winpythontoexec=
rem 2024-08-18: we go initial directory WINPYWORKDIR if no direction and we are on icon directory
rem old NSIS launcher is by default at icon\scripts level
if "%__CD__%scripts\"=="%~dp0" if "%WINPYWORKDIR1%"=="%WINPYDIRBASE%\Notebooks" cd/D %WINPYWORKDIR1%
rem new shimmy launcher is by default at icon level
if "%__CD__%"=="%~dp0" if "%WINPYWORKDIR1%"=="%WINPYDIRBASE%\Notebooks" cd/D %WINPYWORKDIR1%
rem ******************
rem missing student directory part
rem ******************
if not exist "%WINPYWORKDIR%" mkdir "%WINPYWORKDIR%"
if not exist "%HOME%\.spyder-py%WINPYVER:~0,1%" mkdir "%HOME%\.spyder-py%WINPYVER:~0,1%"
if not exist "%HOME%\.spyder-py%WINPYVER:~0,1%\workingdir" echo %HOME%\Notebooks>"%HOME%\.spyder-py%WINPYVER:~0,1%\workingdir"
""",
do_changes=changes,
)
self.create_batch_script(
"Noshell.vbs",
r"""
'from http://superuser.com/questions/140047/how-to-run-a-batch-file-without-launching-a-command-window/390129
If WScript.Arguments.Count >= 1 Then
ReDim arr(WScript.Arguments.Count-1)
For i = 0 To WScript.Arguments.Count-1
Arg = WScript.Arguments(i)
If InStr(Arg, " ") > 0 or InStr(Arg, "&") > 0 Then Arg = chr(34) & Arg & chr(34)
arr(i) = Arg
Next
RunCmd = Join(arr)
CreateObject("Wscript.Shell").Run RunCmd, 0 , True
End If
""",
)
self.create_batch_script(
"WinPythonIni.py", # Replaces winpython.vbs, and a bit of env.bat
r"""
# Prepares a dynamic list of variables settings from a .ini file
import os
import subprocess
from pathlib import Path
winpython_inidefault=r'''
[debug]
state = disabled
[inactive_environment_per_user]
## <?> changing this segment to [active_environment_per_user] makes this segment of lines active or not
HOME = %HOMEDRIVE%%HOMEPATH%\Documents\WinPython%WINPYVER%\settings
USERPROFILE = %HOME%
JUPYTER_DATA_DIR = %HOME%
WINPYWORKDIR = %HOMEDRIVE%%HOMEPATH%\Documents\WinPython%WINPYVER%\Notebooks
[inactive_environment_common]
USERPROFILE = %HOME%
[environment]
## <?> Uncomment lines to override environment variables
#JUPYTERLAB_SETTINGS_DIR = %HOME%\.jupyter\lab
#JUPYTERLAB_WORKSPACES_DIR = %HOME%\.jupyter\lab\workspaces
#R_HOME=%WINPYDIRBASE%\t\R
#R_HOMEbin=%R_HOME%\bin\x64
#JULIA_HOME=%WINPYDIRBASE%\t\Julia\bin\
#JULIA_EXE=julia.exe
#JULIA=%JULIA_HOME%%JULIA_EXE%
#JULIA_PKGDIR=%WINPYDIRBASE%\settings\.julia
#QT_PLUGIN_PATH=%WINPYDIR%\Lib\site-packages\pyqt5_tools\Qt\plugins
'''
def get_file(file_name):
if file_name.startswith("..\\"):
file_name = os.path.join(os.path.dirname(os.path.dirname(__file__)), file_name[3:])
elif file_name.startswith(".\\"):
file_name = os.path.join(os.path.dirname(__file__), file_name[2:])
try:
with open(file_name, 'r') as file:
return file.read()
except FileNotFoundError:
if file_name[-3:] == 'ini':
os.makedirs(Path(file_name).parent, exist_ok=True)
with open(file_name, 'w') as file:
file.write(winpython_inidefault)
return winpython_inidefault
def translate(line, env):
parts = line.split('%')
for i in range(1, len(parts), 2):
if parts[i] in env:
parts[i] = env[parts[i]]
return ''.join(parts)
def main():
import sys
args = sys.argv[1:]
file_name = args[0] if args else "..\\settings\\winpython.ini"
my_lines = get_file(file_name).splitlines()
segment = "environment"
txt = ""
env = os.environ.copy() # later_version: env = os.environ
# default directories (from .bat)
os.makedirs(Path(env['WINPYDIRBASE']) / 'settings' / 'Appdata' / 'Roaming', exist_ok=True)
# default qt.conf for Qt directories
qt_conf='''echo [Paths]