source: trunk/makeBat.py

Last change on this file was 5577, checked in by toby, 5 months ago

finish docs reformatting with changes to G2tools and GSASIIscripts; ReadTheDocs? html now looks good

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Author Revision URL Id
File size: 8.3 KB
Line 
1'''
2This script creates a file named ``RunGSASII.bat`` and a desktop shortcut to that file.
3It registers the filetype .gpx so that the GSAS-II project files exhibit the
4GSAS-II icon and so that double-clicking on them opens them in GSAS-II.
5
6Run this script with no arguments; the path to the ``GSASII.py`` file
7is assumed to be the the same as the path to the ``makeBat.py`` file
8and the path to Python is determined from the version of Python
9used to run this script.
10
11'''
12from __future__ import division, print_function
13version = "$Id: makeBat.py 5577 2023-05-11 23:08:12Z toby $"
14# creates Windows files to aid in running GSAS-II
15#   creates RunGSASII.bat and a desktop shortcut to that file
16#   registers the filetype .gpx so that the GSAS-II project files exhibit the
17#     GSAS-II icon and so that double-clicking on them opens them in GSAS-II
18#
19import os, sys
20import datetime
21import wx
22
23Script = '''@echo ========================================================================
24@echo                General Structure Analysis System-II
25@echo              by Robert B. Von Dreele and Brian H. Toby
26@echo                Argonne National Laboratory(C), 2010
27@echo  This product includes software developed by the UChicago Argonne, LLC,
28@echo             as Operator of Argonne National Laboratory.
29@echo                            Please cite:
30@echo      B.H. Toby and R.B. Von Dreele, J. Appl. Cryst. 46, 544-549 (2013)
31@echo                   for small angle use also cite:
32@echo      R.B. Von Dreele, J. Appl. Cryst. 47, 1784-9 (2014)
33@echo                   for DIFFaX use also cite:
34@echo      M.M.J. Treacy, J.M. Newsam and M.W. Deem,
35@echo                   Proc. Roy. Soc. Lond. 433A, 499-520 (1991)
36@echo ========================================================================
37@
38{:s}{:s} {:s} "%~1"
39@REM To keep the window from disappearing with any error messages
40pause
41
42'''
43
44if __name__ == '__main__':
45    try:
46        import _winreg as winreg
47    except ImportError:
48        import winreg
49    app = None # delay starting wx until we need it. Likely not needed.
50    gsaspath = os.path.split(sys.argv[0])[0]
51    if not gsaspath: gsaspath = os.path.curdir
52    gsaspath = os.path.abspath(os.path.expanduser(gsaspath))
53    G2script = os.path.join(gsaspath,'GSASII.py')
54    G2bat = os.path.join(gsaspath,'RunGSASII.bat')
55    G2icon = os.path.join(gsaspath,'gsas2.ico')
56    pythonexe = os.path.realpath(sys.executable)
57    print('Python installed at',pythonexe)
58    print('GSAS-II installed at',gsaspath)
59    # Bob reports a problem using pythonw.exe w/Canopy on Windows, so change that if used
60    if pythonexe.lower().endswith('pythonw.exe'):
61        print("  using python.exe rather than "+pythonexe)
62        pythonexe = os.path.join(os.path.split(pythonexe)[0],'python.exe')
63        print("  now pythonexe="+pythonexe)
64    # create a GSAS-II script
65    fp = open(os.path.join(G2bat),'w')
66    fp.write("@REM created by run of bootstrap.py on {:%d %b %Y %H:%M}\n".format(
67        datetime.datetime.now()))
68    activate = os.path.join(os.path.split(pythonexe)[0],'Scripts','activate')
69    print("Looking for",activate)
70    if os.path.exists(activate):
71        activate = os.path.realpath(activate)
72        if ' ' in activate:
73            activate = 'call "'+ activate + '"\n'
74        else:
75            activate = 'call '+ activate + '\n'
76        print('adding activate to .bat file ({})'.format(activate))
77    else:
78        print('Anaconda activate not found')
79        activate = ''
80    pexe = pythonexe
81    if ' ' in pythonexe: pexe = '"'+pythonexe+'"'
82    G2s = G2script
83    if ' ' in G2s: G2s = '"'+G2script+'"'
84    # is mingw-w64\bin present? If so add it to path.
85    #d = os.path.split(pexe)[0]
86    #mdir = os.path.join(d,'Library','mingw-w64','bin')
87    #if os.path.exists(mdir):
88    #    fp.write('@path={};%path%\n'.format(mdir))
89    fp.write(Script.format(activate,pexe,G2s))
90    fp.close()
91    print('\nCreated GSAS-II batch file RunGSASII.bat in '+gsaspath)
92   
93    new = False
94    oldBat = ''
95    try: # patch for FileNotFoundError not in Python 2.7
96        FileNotFoundError
97    except NameError:
98        FileNotFoundError = Exception
99    # this code does not appear to work properly when paths have spaces
100    try:
101        oldgpx = winreg.OpenKey(winreg.HKEY_CURRENT_USER,r'Software\CLASSES\GSAS-II.project') # throws FileNotFoundError
102        oldopen = winreg.OpenKey(oldgpx,r'shell\open\command')
103        # get previous value & strip %1 off end
104        oldBat = winreg.QueryValue(oldopen,None).strip()
105        pos = oldBat.rfind(' ')
106        if pos > 1:
107            oldBat = oldBat[:pos]
108        os.stat(oldBat)     #check if it is still around
109    except FileNotFoundError:
110        if oldBat:
111            print('old GPX assignment',oldBat, 'not found; registry entry will be made for new one')
112        new = True
113    if not new:
114        try:
115            if oldBat != G2bat:
116                if app is None:
117                    app = wx.App()
118                    app.MainLoop()
119                dlg = wx.MessageDialog(None,'gpx files already assigned in registry to: \n'+oldBat+'\n Replace with: '+G2bat+'?','GSAS-II gpx in use', 
120                        wx.YES_NO | wx.ICON_QUESTION | wx.STAY_ON_TOP)
121                dlg.Raise()
122                if dlg.ShowModal() == wx.ID_YES:
123                    new = True
124                dlg.Destroy()
125        finally:
126            pass
127    if new:
128        # Associate a script and icon with .gpx files
129        gpxkey = winreg.CreateKey(winreg.HKEY_CURRENT_USER,r'Software\CLASSES\.gpx')
130        winreg.SetValue(gpxkey, None, winreg.REG_SZ, 'GSAS-II.project')
131        winreg.CloseKey(gpxkey)
132        gpxkey = winreg.CreateKey(winreg.HKEY_CURRENT_USER,r'Software\CLASSES\GSAS-II.project')
133        winreg.SetValue(gpxkey, None, winreg.REG_SZ, 'GSAS-II project')
134        iconkey = winreg.CreateKey(gpxkey, 'DefaultIcon')
135        winreg.SetValue(iconkey, None, winreg.REG_SZ, G2icon)
136        openkey = winreg.CreateKey(gpxkey, r'shell\open\command')
137        winreg.SetValue(openkey, None, winreg.REG_SZ, G2bat+' "%1"')
138        winreg.CloseKey(iconkey)
139        winreg.CloseKey(openkey)
140        winreg.CloseKey(gpxkey)
141        print('Assigned icon and batch file to .gpx files in registery')
142    else:
143        print('old assignment of icon and batch file in registery is retained')
144
145    try:
146        import win32com.shell.shell, win32com.shell.shellcon
147        win32com.shell.shell.SHChangeNotify(
148            win32com.shell.shellcon.SHCNE_ASSOCCHANGED, 0, None, None)
149    except ImportError:
150        print('Module pywin32 not present, login again to see file types properly')
151    except:
152        print('Unexpected error on explorer refresh. Please report:')
153        import traceback
154        print(traceback.format_exc())
155
156    # make a desktop shortcut to GSAS-II
157    try:
158        import win32com.shell.shell, win32com.shell.shellcon, win32com.client
159        desktop = win32com.shell.shell.SHGetFolderPath(
160            0, win32com.shell.shellcon.CSIDL_DESKTOP, None, 0)
161        shortbase = "GSAS-II.lnk"
162        shortcut = os.path.join(desktop, shortbase)
163        save = True
164        if win32com.shell.shell.SHGetFileInfo(shortcut,0,0)[0]:
165            print('GSAS-II shortcut exists!')
166            if app is None:
167                app = wx.App()
168                app.MainLoop()
169            dlg = wx.FileDialog(None, 'Choose new GSAS-II shortcut name',  desktop, shortbase,
170                wildcard='GSAS-II shortcut (*.lnk)|*.lnk',style=wx.FD_SAVE|wx.FD_OVERWRITE_PROMPT)
171            dlg.Raise()
172            try:
173                if dlg.ShowModal() == wx.ID_OK:
174                    shortcut = dlg.GetPath()
175                else:
176                    save = False
177            finally:
178                dlg.Destroy()
179        if save:
180            shell = win32com.client.Dispatch('WScript.Shell')
181            shobj = shell.CreateShortCut(shortcut)
182            shobj.Targetpath = G2bat
183            #shobj.WorkingDirectory = wDir # could specify a default project location here
184            shobj.IconLocation = G2icon
185            shobj.save()
186            print('Created shortcut to start GSAS-II on desktop')
187        else:
188            print('No shortcut for this GSAS-II created on desktop')
189    except ImportError:
190        print('Module pywin32 not present, will not make desktop shortcut')
191    except:
192        print('Unexpected error making desktop shortcut. Please report:')
193        import traceback
194        print(traceback.format_exc())
195   
Note: See TracBrowser for help on using the repository browser.