This repository has been archived by the owner on Sep 16, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmakeBat.py
217 lines (207 loc) · 9.27 KB
/
makeBat.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
'''
This script creates a file named ``RunGSASII.bat`` and a desktop shortcut to that file.
It registers the filetype .gpx so that the GSAS-II project files exhibit the
GSAS-II icon and so that double-clicking on them opens them in GSAS-II.
Run this script with no arguments; the path to the ``GSASII.py`` file
is assumed to be the the same as the path to the ``makeBat.py`` file
and the path to Python is determined from the version of Python
used to run this script.
'''
from __future__ import division, print_function
version = "$Id: makeBat.py 5750 2024-03-04 19:37:23Z toby $"
# creates Windows files to aid in running GSAS-II
# creates RunGSASII.bat and a desktop shortcut to that file
# registers the filetype .gpx so that the GSAS-II project files exhibit the
# GSAS-II icon and so that double-clicking on them opens them in GSAS-II
#
import os, sys
import datetime
Script = '''@REM Script to start GSAS-II on Windows
@echo =========================================================================
@echo General Structure Analysis System-II
@echo by Robert B. Von Dreele and Brian H. Toby
@echo Argonne National Laboratory(C), 2006-2014
@echo This product includes software developed by the UChicago Argonne, LLC,
@echo as Operator of Argonne National Laboratory.
@echo Please cite:
@echo B.H. Toby and R.B. Von Dreele, J. Appl. Cryst. 46, 544-549 (2013)
@echo + other papers for DIFFax, small angle, Bilboa, ISODISTORT,... as shown
@echo =========================================================================
@
{:s}{:s} {:s} "%~1"
@REM To keep the window from disappearing with any error messages
pause
'''
app = None # delay starting wx until we need it. Likely not needed.
if __name__ == '__main__':
try:
import winreg
except ImportError:
try:
import _winreg as winreg
except ImportError:
print('winreg not found')
if __file__.lower().endswith("makebat.py"):
print(f"running from file {__file__!r}")
invokedDirectly = True
else:
print(f"running makeBat.py indirectly inside {__file__!r}")
invokedDirectly = False
gsaspath = os.path.dirname(__file__)
if not gsaspath: gsaspath = os.path.curdir
gsaspath = os.path.abspath(os.path.expanduser(gsaspath))
G2script = os.path.join(gsaspath,'GSASII.py')
# when invoked from gitstrap.py, __file__ will appear in the wrong directory
if not os.path.exists(G2script):
gsaspath = os.path.join(gsaspath,'GSASII')
G2script = os.path.join(gsaspath,'GSASII.py')
print(f'patching gsaspath to {gsaspath}')
#
# Hmmm, perhaps we should not create these files in the GSASII directory, which is "owned" by git
# TODO: maybe address in the future
#
G2bat = os.path.join(gsaspath,'RunGSASII.bat')
G2icon = os.path.join(gsaspath,'gsas2.ico')
pythonexe = os.path.realpath(sys.executable)
print('Python installed at',pythonexe)
print('GSAS-II installed at',gsaspath)
# Bob reports a problem using pythonw.exe w/Canopy on Windows, so change that if used
if pythonexe.lower().endswith('pythonw.exe'):
print(" using python.exe rather than "+pythonexe)
pythonexe = os.path.join(os.path.split(pythonexe)[0],'python.exe')
print(" now pythonexe="+pythonexe)
# create a GSAS-II script
fp = open(G2bat,'w')
fp.write("@REM created by run of bootstrap.py on {:%d %b %Y %H:%M}\n".format(
datetime.datetime.now()))
activate = os.path.join(os.path.split(pythonexe)[0],'Scripts','activate')
print("Looking for",activate)
# for a non-base conda install, it might be better to use the activate in
# the base, but for now let's use the one we find relative to our python
if os.path.exists(activate):
activate = os.path.realpath(activate)
if ' ' in activate:
activate = 'call "'+ activate + '"\n'
else:
activate = 'call '+ activate + '\n'
print(f'adding activate to .bat file ({activate})')
else:
print('conda activate not found')
activate = ''
pexe = pythonexe
if ' ' in pythonexe: pexe = '"'+pythonexe+'"'
G2s = G2script
if ' ' in G2s: G2s = '"'+G2script+'"'
fp.write(Script.format(activate,pexe,G2s))
fp.close()
print('\nCreated GSAS-II batch file RunGSASII.bat in '+gsaspath)
new = False
oldBat = ''
# this code does not appear to work properly when paths have spaces
try:
oldgpx = winreg.OpenKey(winreg.HKEY_CURRENT_USER,r'Software\CLASSES\GSAS-II.project') # throws FileNotFoundError
oldopen = winreg.OpenKey(oldgpx,r'shell\open\command')
# get previous value & strip %1 off end
oldBat = winreg.QueryValue(oldopen,None).strip()
pos = oldBat.rfind(' ')
if pos > 1:
oldBat = oldBat[:pos]
os.stat(oldBat) #check if it is still around
except FileNotFoundError:
if oldBat:
print('old GPX assignment',oldBat, 'not found; registry entry will be made for new one')
new = True
except NameError:
pass
if invokedDirectly and not new:
try:
if oldBat != G2bat:
if app is None:
import wx
app = wx.App()
dlg = wx.MessageDialog(None,'gpx files already assigned in registry to: \n'+oldBat+'\n Replace with: '+G2bat+'?','GSAS-II gpx in use',
wx.YES_NO | wx.ICON_QUESTION | wx.STAY_ON_TOP)
dlg.Raise()
if dlg.ShowModal() == wx.ID_YES:
new = True
dlg.Destroy()
finally:
pass
elif not invokedDirectly: # force if we can't ask
new = True
if new:
# Associate a script and icon with .gpx files
try:
gpxkey = winreg.CreateKey(winreg.HKEY_CURRENT_USER,r'Software\CLASSES\.gpx')
winreg.SetValue(gpxkey, None, winreg.REG_SZ, 'GSAS-II.project')
winreg.CloseKey(gpxkey)
gpxkey = winreg.CreateKey(winreg.HKEY_CURRENT_USER,r'Software\CLASSES\GSAS-II.project')
winreg.SetValue(gpxkey, None, winreg.REG_SZ, 'GSAS-II project')
iconkey = winreg.CreateKey(gpxkey, 'DefaultIcon')
winreg.SetValue(iconkey, None, winreg.REG_SZ, G2icon)
openkey = winreg.CreateKey(gpxkey, r'shell\open\command')
winreg.SetValue(openkey, None, winreg.REG_SZ, G2bat+' "%1"')
winreg.CloseKey(iconkey)
winreg.CloseKey(openkey)
winreg.CloseKey(gpxkey)
print('Assigned icon and batch file to .gpx files in registry')
except:
print('Error assigning icon and batch file to .gpx files')
else:
print('old assignment of icon and batch file in registery is retained')
try:
import win32com.shell.shell, win32com.shell.shellcon
win32com.shell.shell.SHChangeNotify(
win32com.shell.shellcon.SHCNE_ASSOCCHANGED, 0, None, None)
except ImportError:
print('Module pywin32 not present, login again to see file types properly')
except:
print('Unexpected error on explorer refresh.')
import traceback
print(traceback.format_exc())
# make a desktop shortcut to GSAS-II
try:
import win32com.shell.shell, win32com.shell.shellcon, win32com.client
desktop = win32com.shell.shell.SHGetFolderPath(
0, win32com.shell.shellcon.CSIDL_DESKTOP, None, 0)
shortbase = "GSAS-II.lnk"
shortcut = os.path.join(desktop, shortbase)
save = True
if win32com.shell.shell.SHGetFileInfo(shortcut,0,0)[0]:
print('GSAS-II shortcut exists!')
if invokedDirectly:
if app is None:
import wx
app = wx.App()
dlg = wx.FileDialog(None, 'Choose new GSAS-II shortcut name', desktop, shortbase,
wildcard='GSAS-II shortcut (*.lnk)|*.lnk',style=wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT)
dlg.Raise()
try:
if dlg.ShowModal() == wx.ID_OK:
shortcut = dlg.GetPath()
else:
save = False
finally:
dlg.Destroy()
else:
# set an installation location
distdir = os.path.split(os.path.dirname(gsaspath))[1]
if distdir == '\\' or distdir == '': distdir = '/'
shortbase = f"GSAS-II from {distdir}.lnk"
shortcut = os.path.join(desktop, shortbase)
if save:
shell = win32com.client.Dispatch('WScript.Shell')
shobj = shell.CreateShortCut(shortcut)
shobj.Targetpath = G2bat
#shobj.WorkingDirectory = wDir # could specify a default project location here
shobj.IconLocation = G2icon
shobj.save()
print(f'Created shortcut {shortbase!r} to start GSAS-II on desktop')
else:
print('No shortcut for this GSAS-II created on desktop')
except ImportError:
print('Module pywin32 not present, will not make desktop shortcut')
except:
print('Unexpected error making desktop shortcut.')
import traceback
print(traceback.format_exc())