source: trunk/makeBat.py @ 4266

Last change on this file since 4266 was 4266, checked in by toby, 21 months ago

add patches for Python 2.7

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