source: install/g2complete/src/bootstrap.py @ 4771

Last change on this file since 4771 was 4771, checked in by toby, 3 years ago

fixes for windows g2complete

  • Property svn:eol-style set to native
  • Property svn:executable set to *
  • Property svn:keywords set to Date Author Revision URL Id
File size: 26.5 KB
Line 
1#!/usr/bin/env python
2# Installs GSAS-II from network using subversion and creates platform-specific shortcuts.
3# works for Mac & Linux & Windows
4from __future__ import division, print_function
5import os, stat, sys, platform, subprocess, datetime
6
7version = "$Id: bootstrap.py 4771 2021-01-16 16:17:50Z toby $"
8g2home = 'https://subversion.xray.aps.anl.gov/pyGSAS/'
9path2GSAS2 = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))
10
11skipInstallChecks = False  # if set to True, continue installation even if current Python lacks packages and
12                           # skips platform-dependent installation steps
13                           #--> True: -noinstall or -binary=
14skipDownloadSteps = False  # if False, svn is used to download GSAS-II files and binaries
15                           #--> True: -nonet
16skipProxy = False          # if False then the script creates a prompt asking for proxy info
17                           #--> True: -nonet or -noproxy or -binary=
18showWXerror = False        # if True, errors are shown in wxPython windows (used on Windows only)
19                           #--> True: -noinstall or -binary= (both on windows)
20help = False               # if True, a help message is shown
21                           #--> True: -help
22allBinaries = False        # if True, causes all binaries to be installed
23                           #--> True: -allbinaries or -server
24
25npVersion=None          # when set, gives a specific numpy version to use (such as 1.18)
26                           # for selecting a set of binaries to use
27                           #--> Set by: -binary=
28
29pyVersion=None             # when set, gives a specific Python version to use (such as 3.7)
30                           # for selecting a set of binaries to use
31                           #--> Set by: -binary=
32
33
34for a in sys.argv[1:]:
35    if 'noinstall' in a.lower():
36        skipInstallChecks = True
37        if sys.platform.startswith('win'): showWXerror = True
38    elif 'nonet' in a.lower():
39        skipDownloadSteps = True
40        skipProxy = True
41    elif 'noproxy' in a.lower():
42        skipProxy = True
43    elif 'allbin' in a.lower() or 'server' in a.lower():
44        allBinaries = True
45    elif 'binary' in a.lower():
46        vers = a.split('=')[1].split(',')
47        npVersion = vers[0]
48        if len(vers) > 1:
49            pyVersion = vers[1]
50            print('Selecting Python binary',pyVersion)
51        print('Selecting numpy binary',npVersion)
52        skipInstallChecks = True
53        if sys.platform.startswith('win'): showWXerror = True
54        skipProxy = True
55    else:
56        help = True
57    if 'help' in a.lower():
58        help = True
59
60if help:
61    print('''
62  bootstrap.py options:
63
64    --noinstall   skip post-install, such as creating run shortcuts, turns on
65                  wxpython error display in Windows
66    --noproxy     do not ask for proxy information
67    --server      load all binary versions
68    --allbin      load all binary versions (same as --server)
69    --help        this message
70    --nonet       skip steps requiring internet
71
72    --binary=npver          specifies a specific numpy/python version to use in selecting
73    --binary=npver,pyver    a binary directory to use ; turns on --noinstall and --noproxy
74           (example --binary=1.18 or --binary=1.18,3.7)
75           turns on --noinstall and --noproxy
76''')
77    sys.exit()
78
79now = str(datetime.datetime.now())
80print('Running bootstrap from {} at {}\n\tId: {}'.format(path2GSAS2,now,version))
81print ("Python:     %s"%sys.version.split()[0])
82try:
83    import numpy as np
84    print ("numpy:      %s"%np.__version__)
85except:
86    pass
87fp = open(os.path.join(path2GSAS2,'bootstrap.log'),'a')
88fp.write('Running bootstrap from {} at {}\n\tId: {}\n'.format(path2GSAS2,now,version))
89fp.close()
90       
91################################################################################
92################################################################################
93def BailOut(msg):
94    '''Exit with an error message. Use a GUI to show the error when
95    showWXerror == True (on windows when --noinstall is specified)
96    '''
97    print(msg)
98    if showWXerror:
99        import wx
100        app = wx.App()
101        app.MainLoop()
102        dlg = wx.MessageDialog(None,msg,'GSAS-II installation error', 
103                wx.OK | wx.ICON_ERROR | wx.STAY_ON_TOP)
104        dlg.Raise()
105        dlg.ShowModal()
106        dlg.Destroy()
107    else:
108        print("Recreate error this using command:")
109        print("     {} {} {}".format(
110            os.path.abspath(sys.executable),
111            os.path.abspath(os.path.expanduser(__file__)),
112            ' '.join(sys.argv[1:]),
113        ),file=sys.stderr)
114        print("\nBOOTSTRAP WARNING: ",file=sys.stderr)
115        for line in msg.split('\n'):
116            print(line,file=sys.stderr)
117    sys.exit()
118       
119def GetConfigValue(*args): return True
120# routines copied from GSASIIpath.py
121proxycmds = []
122'Used to hold proxy information for subversion, set if needed in whichsvn'
123svnLocCache = None
124'Cached location of svn to avoid multiple searches for it'
125
126def MakeByte2str(arg):
127    '''Convert output from subprocess pipes (bytes) to str (unicode) in Python 3.
128    In Python 2: Leaves output alone (already str).
129    Leaves stuff of other types alone (including unicode in Py2)
130    Works recursively for string-like stuff in nested loops and tuples.
131
132    typical use::
133
134        out = MakeByte2str(out)
135
136    or::
137
138        out,err = MakeByte2str(s.communicate())
139   
140    '''
141    if isinstance(arg,str): return arg
142    if isinstance(arg,bytes):
143        try:
144            return arg.decode()
145        except:
146            print('Decode error')
147            return arg
148    if isinstance(arg,list):
149        return [MakeByte2str(i) for i in arg]
150    if isinstance(arg,tuple):
151        return tuple([MakeByte2str(i) for i in arg])
152    return arg
153
154def getsvnProxy():
155    '''Loads a proxy for subversion from the file created by bootstrap.py
156    '''
157    global proxycmds
158    proxycmds = []
159    proxyinfo = os.path.join(os.path.expanduser('~/.G2local/'),"proxyinfo.txt")
160    if not os.path.exists(proxyinfo):
161        proxyinfo = os.path.join(path2GSAS2,"proxyinfo.txt")
162    if not os.path.exists(proxyinfo):
163        return '','',''
164    fp = open(proxyinfo,'r')
165    host = fp.readline().strip()
166    # allow file to begin with comments
167    while host.startswith('#'):
168        host = fp.readline().strip()
169    port = fp.readline().strip()
170    etc = []
171    line = fp.readline()
172    while line:
173        etc.append(line.strip())
174        line = fp.readline()
175    fp.close()
176    setsvnProxy(host,port,etc)
177    return host,port,etc
178
179def setsvnProxy(host,port,etc=[]):
180    '''Sets the svn commands needed to use a proxy
181    '''
182    global proxycmds
183    proxycmds = []
184    host = host.strip()
185    port = port.strip()
186    if host: 
187        proxycmds.append('--config-option')
188        proxycmds.append('servers:global:http-proxy-host='+host)
189        if port:
190            proxycmds.append('--config-option')
191            proxycmds.append('servers:global:http-proxy-port='+port)
192    for item in etc:
193        proxycmds.append(item)
194       
195def whichsvn():
196    '''Returns a path to the subversion exe file, if any is found.
197    Searches the current path after adding likely places where GSAS-II
198    might install svn.
199
200    :returns: None if svn is not found or an absolute path to the subversion
201      executable file.
202    '''
203    # use a previosuly cached svn location
204    global svnLocCache
205    if svnLocCache: return svnLocCache
206    # prepare to find svn
207    is_exe = lambda fpath: os.path.isfile(fpath) and os.access(fpath, os.X_OK)
208    svnprog = 'svn'
209    if sys.platform.startswith('win'): svnprog += '.exe'
210    host,port,etc = getsvnProxy()
211    if GetConfigValue('debug') and host:
212        print('DBG_Using proxy host {} port {}'.format(host,port))
213    # add likely places to find subversion when installed with GSAS-II
214    pathlist = os.environ["PATH"].split(os.pathsep)
215    pathlist.insert(0,os.path.split(sys.executable)[0])
216    pathlist.insert(1,path2GSAS2)
217    for rpt in ('..','bin'),('..','Library','bin'),('svn','bin'),('svn',),('.'):
218        pt = os.path.normpath(os.path.join(path2GSAS2,*rpt))
219        if os.path.exists(pt):
220            pathlist.insert(0,pt)   
221    # search path for svn or svn.exe
222    for path in pathlist:
223        exe_file = os.path.join(path, svnprog)
224        if is_exe(exe_file):
225            try:
226                p = subprocess.Popen([exe_file,'help'],stdout=subprocess.PIPE)
227                res = p.stdout.read()
228                p.communicate()
229                svnLocCache = os.path.abspath(exe_file)
230                return svnLocCache
231            except:
232                pass       
233    svnLocCache = None
234
235def svnVersion(svn=None):
236    '''Get the version number of the current subversion executable
237
238    :returns: a string with a version number such as "1.6.6" or None if
239      subversion is not found.
240
241    '''
242    if not svn: svn = whichsvn()
243    if not svn: return
244
245    cmd = [svn,'--version','--quiet']
246    s = subprocess.Popen(cmd,
247                         stdout=subprocess.PIPE,stderr=subprocess.PIPE)
248    out,err = MakeByte2str(s.communicate())
249    if err:
250        print ('subversion error!\nout=%s'%out)
251        print ('err=%s'%err)
252        s = '\nsvn command:  '
253        for i in cmd: s += i + ' '
254        print(s)
255        return None
256    return out.strip()
257
258def svnVersionNumber(svn=None):
259    '''Get the version number of the current subversion executable
260
261    :returns: a fractional version number such as 1.6 or None if
262      subversion is not found.
263
264    '''
265    ver = svnVersion(svn)
266    if not ver: return 
267    M,m = ver.split('.')[:2]
268    return int(M)+int(m)/10.
269
270def showsvncmd(cmd):
271    s = '\nsvn command:  '
272    for i in cmd: s += i + ' '
273    print(s)
274
275def svncleanup(spath,svn=None):
276    if not svn: svn = whichsvn()
277    if not svn: return
278    svntmp = os.path.join(spath,'.svn','tmp')
279    if os.path.exists(os.path.join(spath,'.svn')) and not os.path.exists(svntmp):
280        print('missing subversion tmp directory, fixing')       
281        cmd = ['mkdir',svntmp]
282        s = subprocess.Popen(cmd,stderr=subprocess.PIPE)
283        out,err = MakeByte2str(s.communicate())
284        if out: print(out)
285        if err: print(err)
286    if os.path.exists(os.path.join(spath,'.svn')):
287        cmd = [svn, 'cleanup', spath]
288        s = subprocess.Popen(cmd,stderr=subprocess.PIPE)
289        out,err = MakeByte2str(s.communicate())
290        if err:
291            print('subversion cleanup returned an error:')
292            if out: print(out)
293            if err: print(err)
294
295def svnChecksumPatch(svn,fpath,verstr):
296    '''This performs a fix when svn cannot finish an update because of
297    a Checksum mismatch error. This seems to be happening on OS X for
298    unclear reasons.
299    '''
300    svntmp = os.path.join(fpath,'.svn','tmp')
301    if not os.path.exists(svntmp):
302        print('missing subversion tmp directory')
303    print('\nAttempting patch for svn Checksum mismatch error\n')
304    svncleanup(fpath)
305    cmd = ['svn','update','--set-depth','empty',
306               os.path.join(fpath,'bindist')]
307    showsvncmd(cmd)       
308    s = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
309    out,err = MakeByte2str(s.communicate())
310    print(svntmp, os.path.exists(svntmp))
311    #if err: print('error=',err)
312    try:
313        import GSASIIpath
314        print('import of GSASIIpath completed')
315    except Exception as err:
316        msg = 'Failed with import of GSASIIpath in svnChecksumPatch. This is unexpected.'
317        msg += '\nGSAS-II will not run without correcting this. Contact toby@anl.gov'
318        print(err)
319        BailOut(msg)
320    cmd = ['svn','switch',g2home+'/trunk/bindist',
321               os.path.join(fpath,'bindist'),
322               '--non-interactive', '--trust-server-cert', '--accept',
323               'theirs-conflict', '--force', '-rHEAD', '--ignore-ancestry']
324    showsvncmd(cmd)       
325    s = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
326    out,err = MakeByte2str(s.communicate())
327    GSASIIpath.DownloadG2Binaries(g2home,verbose=True)
328    cmd = ['svn','update','--set-depth','infinity',
329               os.path.join(fpath,'bindist')]
330    showsvncmd(cmd)       
331    s = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
332    out,err = MakeByte2str(s.communicate())
333    #if err: print('error=',err)
334    cmd = [svn,'update',fpath,verstr,
335                       '--non-interactive',
336                       '--accept','theirs-conflict','--force']
337    if svnVersionNumber() >= 1.6:
338        cmd += ['--trust-server-cert']
339    if proxycmds: cmd += proxycmds
340    #print(cmd)
341    showsvncmd(cmd)       
342    s = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
343    out,err = MakeByte2str(s.communicate())
344    #if err: print('error=',err)
345    return err
346
347################################################################################
348################################################################################
349print(70*'*')
350#testing for incorrect locale code'
351try:
352    import locale
353    locale.getdefaultlocale()
354except ValueError:
355    print('Your location is not set properly. This causes problems for matplotlib')
356    print('  (see https://github.com/matplotlib/matplotlib/issues/5420.)')
357    print('Will try to bypass problem by setting LC_ALL to en_US.UTF-8 (US English)')
358    os.environ['LC_ALL'] = 'en_US.UTF-8'
359    locale.getdefaultlocale()
360print('Preloading matplotlib to build fonts...')
361try:
362    import matplotlib
363except:
364    pass
365print('Checking python packages...')
366missing = []
367for pkg in ['numpy','scipy','matplotlib','wx','OpenGL',]:
368    try:
369        exec('import '+pkg)
370    except:
371        missing.append(pkg)
372
373if missing and not skipInstallChecks:
374    msg = """Sorry, this version of Python cannot be used
375for GSAS-II. It is missing the following package(s):
376\t"""
377    for pkg in missing: msg += " "+pkg
378    msg += "\nPlease install these package(s) and try running bootstrap.py again."
379    #print("Showing first error: ")
380    #for pkg in ['numpy','scipy','matplotlib','wx','OpenGL',]:
381    #    exec('import '+pkg)
382    BailOut(msg)
383
384if not skipDownloadSteps:
385    host = None
386    port = '80'
387    print('\nChecking for subversion...')
388    svn = whichsvn() # resets host & port if proxyinfo.txt is found
389    if not svn:
390        msg ="Sorry, subversion (svn) could not be found on your system."
391        msg += "\nPlease install this or place in path and rerun this."
392        BailOut(msg)
393    else:
394        print(' found svn image: '+svn)
395
396#if install_with_easyinstall:           
397#    print('\nInstalling PyOpenGL. Lots of warnings will follow... ')
398#    install_with_easyinstall('PyOpenGl')               
399#    print('done.')
400   
401print('Ready to bootstrap GSAS-II from repository\n\t'+g2home+'\nto '+path2GSAS2)
402proxycmds = []
403host,port,etc = getsvnProxy()
404if sys.version_info[0] == 2:
405    getinput = raw_input
406else:
407    getinput = input
408
409# get proxy setting from environment variable
410key = None
411for i in os.environ.keys():
412    if 'https_proxy' == i.lower():
413        key = i
414        break
415else:
416    for i in os.environ.keys():
417        if 'http_proxy' == i.lower():
418            key = i
419            break
420val = ''
421if key:
422    val = os.environ[key].strip()
423if val:
424    if val[-1] == '/':
425        val = val[:-1]
426    if len(val.split(':')) > 2:
427        host = ':'.join(val.split(':')[:-1])
428        port = val.split(':')[-1]
429    else:
430        host = ':'.join(val.split(':')[:-1])
431        port = val.split(':')[-1]
432
433# get proxy from user, if terminal available
434try:
435    if skipProxy:
436        host = ""
437    elif host:
438        print('\n'+75*'*')
439        ans = getinput("Enter the proxy address (type none to remove) ["+host+"]: ").strip()
440        if ans.lower() == "none": host = ""
441    else:
442        ans = getinput("Enter your proxy address [none needed]: ").strip()
443        if ans: host = ans
444    if host:
445        ans = getinput("Enter the proxy port ["+port+"]: ").strip()
446        if ans == "": ans=port
447        port = ans
448        print('If your site needs additional svn commands (such as \n\t',
449                  '--config-option servers:global:http-proxy-username=*account*','\n\t',
450                  '--config-option servers:global:http-proxy-password=*password*',
451                  '\nenter them now:')
452        if etc:
453            prevetc = ' '.join(etc)
454            print('\nDefault for next input is "{}"'.format(prevetc))
455            prompt = "Enter additional svn options (if any) [use previous]: "
456        else:
457            prompt = "Enter additional svn options (if any) [none]: "
458        ans = 'start'
459        etcstr = ''
460        while ans:
461            ans = getinput(prompt).strip()
462            prompt = "more svn options (if any): "
463            if etcstr: etcstr += ' '
464            etcstr += ans
465        if etcstr.strip():
466           etc = etcstr.split()
467except EOFError:
468    host = ""
469    port = ""
470    etc = []
471setsvnProxy(host,port,etc)
472# delete old proxy files
473localproxy = os.path.join(os.path.expanduser('~/.G2local/'),"proxyinfo.txt")
474for proxyinfo in localproxy,os.path.join(path2GSAS2,"proxyinfo.txt"):
475    if os.path.exists(proxyinfo):
476        try:
477            os.remove(proxyinfo)
478            print('Deleted file {}'.format(proxyinfo))
479        except:
480            pass
481if host:
482    try:
483        fp = open(proxyinfo,'w')
484    except:
485        fp = open(localproxy,'w')
486        proxyinfo = localproxy
487    try:
488        fp.write(host.strip()+'\n')
489        fp.write(port.strip()+'\n')
490        for i in etc:
491            if i.strip():
492                fp.write(i.strip()+'\n')
493        fp.close()
494        msg = 'Proxy info written: {} port {} etc {}\n'.format(host,port,etc)
495        print(msg)
496        fp = open(os.path.join(path2GSAS2,'bootstrap.log'),'a')
497        fp.write(msg)
498        fp.close()
499    except Exception as err:
500        print('Error writing file {}:\n{}'.format(proxyinfo,err))
501       
502if not skipDownloadSteps:
503    # patch: switch GSAS-II location if linked to XOR server (relocated May/June 2017)
504    cmd = [svn, 'info',path2GSAS2]
505    p = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
506    res,err = p.communicate()
507    if '.xor.' in str(res):
508        print('Switching previous install with .xor. download location to\n\thttps://subversion.xray.aps.anl.gov/pyGSAS')
509        cmd = [svn, 'switch','--relocate','https://subversion.xor.aps.anl.gov/pyGSAS',
510               'https://subversion.xray.aps.anl.gov/pyGSAS',path2GSAS2]
511        if proxycmds: cmd += proxycmds
512        p = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
513        res,err = p.communicate()
514        if err:
515            print('Please report this error to toby@anl.gov:')
516            print(err)
517            print(res)
518    # patch: switch GSAS-II location if switched to 2frame version (removed August 2017)
519    elif '2frame' in str(res):
520        print('Switching previous 2frame install to trunk\n\thttps://subversion.xray.aps.anl.gov/pyGSAS')
521        cmd = [svn, 'switch',g2home + '/trunk',path2GSAS2,
522               '--non-interactive','--trust-server-cert',
523               '--accept','theirs-conflict','--force','--ignore-ancestry']
524        if proxycmds: cmd += proxycmds
525        p = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
526        res,err = p.communicate()
527        if err:
528            print('Please report this error to toby@anl.gov:')
529            print(err)
530            print(res)
531    elif 'not a working' not in str(res):
532        svncleanup(path2GSAS2)
533
534    print('\n'+75*'*')
535    print('Now preparing to install GSAS-II')
536    tryagain = True
537    err = False
538    firstPass = 0
539    while(tryagain):
540        tryagain = False
541        if err:
542            print('Retrying after a cleanup...')
543            svncleanup(path2GSAS2)
544        cmd = [svn, 'co', g2home+ 'trunk/', path2GSAS2, '--non-interactive', '--trust-server-cert']
545        if proxycmds: cmd += proxycmds
546        msg = 'svn load command: '
547        for item in cmd: msg += " "+item
548        print(msg)
549        s = subprocess.Popen(cmd,stderr=subprocess.PIPE)
550        print('\nsubversion output:')
551        out,err = MakeByte2str(s.communicate())
552        if 'Checksum' in err:  # deal with Checksum problem
553            err = svnChecksumPatch(svn,path2GSAS2,'-rHEAD')
554            if err:
555                print('error from svnChecksumPatch\n\t',err)
556        elif err:
557            print('subversion returned an error:')
558            print(out)
559            print(err)
560            if firstPass == 0: tryagain = True
561        firstPass += 1
562    if err:
563        print('Retrying with a command for older svn version...')
564        cmd = [svn, 'co', g2home+ 'trunk/', path2GSAS2]
565        if proxycmds: cmd += proxycmds
566        msg = ""
567        for item in cmd: msg += " " + item
568        print(msg)
569        s = subprocess.Popen(cmd,stderr=subprocess.PIPE)
570        out,err = MakeByte2str(s.communicate())
571        if err:
572            msg = 'subversion returned an error:\n'
573            msg += err
574            if os.path.exists(os.path.join(path2GSAS2,"makeBat.py")):
575                msg += '\nGSAS-II appears to be installed but failed to be updated. A likely reason'
576                msg += '\nis a network access problem. If your web browser works, but this update did'
577                msg += '\nnot, the most common reason is you need to use a network proxy. Please'
578                msg += '\ncheck with a network administrator or use http://www.whatismyproxy.com/'
579                msg += '\n\nIf installing from the gsas2full dist and your computer is not connected'
580                msg += '\nto the internet, this error message can be ignored.\n'
581            else:
582                # this will happen only with initial installs where all files
583                # are to be downloaded (not gsas2full or updates)
584                msg += '\n\n  *** GSAS-II failed to be installed. A likely reason is a network access'
585                msg += '\n  *** problem, most commonly because you need to use a network proxy. Please'
586                msg += '\n  *** check with a network administrator or use http://www.whatismyproxy.com/\n'
587            BailOut(msg)
588    print('\n'+75*'*')
589else:
590    svncleanup(path2GSAS2)
591
592# subsequent commands require GSASIIpath which better be here now, import it
593try:
594    import GSASIIpath
595    print('import of GSASIIpath completed')
596except Exception as err:
597    msg = 'Failed with import of GSASIIpath. This is unexpected.'
598    msg += '\nGSAS-II will not run without correcting this. Contact toby@anl.gov'
599    print('GSASIIpath import error\n')
600    print(err)
601    BailOut(msg)
602
603if skipDownloadSteps:
604    pass
605elif allBinaries:
606    print('Loading all binaries with command...')
607    if not GSASIIpath.svnSwitchDir('AllBinaries','',g2home+ 'Binaries/',None,True):
608        msg = 'Binary load failed. Subversion problem? Please seek help'
609        BailOut(msg)
610elif npVersion:
611    binaryVersion = GSASIIpath.GetBinaryPrefix(pyVersion)+'_n'+npVersion
612    print('Load binaries from '+binaryVersion)
613    if not GSASIIpath.svnSwitchDir('bindist','',g2home+ 'Binaries/'+binaryVersion,None,True):
614        msg = 'Binary load failed with '+binaryVersion+'. Subversion problem? Please seek help'
615        BailOut(msg)
616else:
617    print('Load binaries matching current python/numpy')
618    GSASIIpath.DownloadG2Binaries(g2home)
619       
620#===========================================================================
621# test if the compiled files load correctly
622#===========================================================================
623GSASIItested = False
624if not skipInstallChecks:
625    script = """ 
626# commands that test each module can at least be loaded & run something in pyspg
627try:
628    import GSASIIpath
629    GSASIIpath.SetBinaryPath(loadBinary=False)
630    import pyspg
631    import histogram2d
632    import polymask
633    import pypowder
634    import pytexture
635    pyspg.sgforpy('P -1')
636    print('==OK==')
637except Exception as err:
638    print(err)
639"""
640    p = subprocess.Popen([sys.executable,'-c',script],stdout=subprocess.PIPE,stderr=subprocess.PIPE,
641                         cwd=path2GSAS2)
642    res,err = MakeByte2str(p.communicate())
643    if '==OK==' not in str(res) or p.returncode != 0:
644        #print('\n'+75*'=')
645        msg = 'Failed when testing the GSAS-II compiled files. GSAS-II will not run'
646        msg += ' without correcting this.\n\nError message:\n'
647        if res: 
648            msg += res
649            msg += '\n'
650        if err:
651            msg += err
652        #print('\nAttempting to open a web page on compiling GSAS-II...')
653        msg += '\n\nPlease see web page\nhttps://subversion.xray.aps.anl.gov/trac/pyGSAS/wiki/CompileGSASII if you wish to compile for yourself (usually not needed for windows and Mac, but sometimes required for Linux.)'
654        BailOut(msg)
655        #import webbrowser
656        #webbrowser.open_new('https://subversion.xray.aps.anl.gov/trac/pyGSAS/wiki/CompileGSASII')
657        #print(75*'=')
658    #    if '86' in platform.machine() and (sys.platform.startswith('linux')
659    #                                        or sys.platform == "darwin"
660    #                                        or sys.platform.startswith('win')):
661    #        print('Platform '+sys.platform+' with processor type '+platform.machine()+' is supported')
662    #    else:
663    #        print('Platform '+sys.platform+' with processor type '+platform.machine()+' not is supported')
664    else:
665        print('Successfully tested compiled routines')
666        GSASIItested = True
667#===========================================================================
668# import all .py files so that .pyc files get created
669if not skipInstallChecks:
670    print('Byte-compiling all .py files...')
671    import compileall
672    compileall.compile_dir(path2GSAS2,quiet=True)
673    print('done')
674#===========================================================================
675# do platform-dependent stuff
676#===========================================================================
677if sys.version_info[0] > 2:
678    def execfile(file):
679        with open(file) as source_file:
680            exec(source_file.read())
681
682#===========================================================================
683# on Windows, make a batch file with Python and GSAS-II location hard-coded
684if skipInstallChecks:
685    pass
686elif sys.platform.startswith('win') and os.path.exists(
687    os.path.join(path2GSAS2,"makeBat.py")):
688    execfile(os.path.join(path2GSAS2,"makeBat.py"))
689#===========================================================================
690# on a Mac, make an applescript
691elif sys.platform.startswith('darwin') and os.path.exists(
692         os.path.join(path2GSAS2,"makeMacApp.py")):
693    sys.argv = [os.path.join(path2GSAS2,"makeMacApp.py")]
694    print(u'running '+sys.argv[0])
695    execfile(sys.argv[0])
696#===========================================================================
697# On linux, make desktop icon
698elif sys.platform.startswith('linux') and os.path.exists(
699         os.path.join(path2GSAS2,"makeLinux.py")):
700    sys.argv = [os.path.join(path2GSAS2,"makeLinux.py")]
701    print(u'running '+sys.argv[0])
702    execfile(sys.argv[0])
703
Note: See TracBrowser for help on using the repository browser.