source: install/bootstrap.py @ 5105

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

more bootstrap fixes

  • Property svn:eol-style set to native
  • Property svn:keywords set to Date Author Revision URL Id
File size: 26.3 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 4775 2021-01-16 18:52:00Z vondreele $"
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        os.makedirs(svntmp,exist_ok=True)
282    if os.path.exists(os.path.join(spath,'.svn')):
283        cmd = [svn, 'cleanup', spath]
284        s = subprocess.Popen(cmd,stderr=subprocess.PIPE)
285        out,err = MakeByte2str(s.communicate())
286        if err:
287            print('subversion cleanup returned an error:')
288            if out: print(out)
289            if err: print(err)
290
291def svnChecksumPatch(svn,fpath,verstr):
292    '''This performs a fix when svn cannot finish an update because of
293    a Checksum mismatch error. This seems to be happening on OS X for
294    unclear reasons.
295    '''
296    svntmp = os.path.join(fpath,'.svn','tmp')
297    if not os.path.exists(svntmp):
298        print('missing subversion tmp directory')
299    print('\nAttempting patch for svn Checksum mismatch error\n')
300    svncleanup(fpath)
301    cmd = ['svn','update','--set-depth','empty',
302               os.path.join(fpath,'bindist')]
303    showsvncmd(cmd)       
304    s = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
305    out,err = MakeByte2str(s.communicate())
306    print(svntmp, os.path.exists(svntmp))
307    #if err: print('error=',err)
308    try:
309        import GSASIIpath
310        print('import of GSASIIpath completed')
311    except Exception as err:
312        msg = 'Failed with import of GSASIIpath in svnChecksumPatch. This is unexpected.'
313        msg += '\nGSAS-II will not run without correcting this. Contact toby@anl.gov'
314        print(err)
315        BailOut(msg)
316    cmd = ['svn','switch',g2home+'/trunk/bindist',
317               os.path.join(fpath,'bindist'),
318               '--non-interactive', '--trust-server-cert', '--accept',
319               'theirs-conflict', '--force', '-rHEAD', '--ignore-ancestry']
320    showsvncmd(cmd)       
321    s = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
322    out,err = MakeByte2str(s.communicate())
323    GSASIIpath.DownloadG2Binaries(g2home,verbose=True)
324    cmd = ['svn','update','--set-depth','infinity',
325               os.path.join(fpath,'bindist')]
326    showsvncmd(cmd)       
327    s = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
328    out,err = MakeByte2str(s.communicate())
329    #if err: print('error=',err)
330    cmd = [svn,'update',fpath,verstr,
331                       '--non-interactive',
332                       '--accept','theirs-conflict','--force']
333    if svnVersionNumber() >= 1.6:
334        cmd += ['--trust-server-cert']
335    if proxycmds: cmd += proxycmds
336    #print(cmd)
337    showsvncmd(cmd)       
338    s = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
339    out,err = MakeByte2str(s.communicate())
340    #if err: print('error=',err)
341    return err
342
343################################################################################
344################################################################################
345print(70*'*')
346#testing for incorrect locale code'
347try:
348    import locale
349    locale.getdefaultlocale()
350except ValueError:
351    print('Your location is not set properly. This causes problems for matplotlib')
352    print('  (see https://github.com/matplotlib/matplotlib/issues/5420.)')
353    print('Will try to bypass problem by setting LC_ALL to en_US.UTF-8 (US English)')
354    os.environ['LC_ALL'] = 'en_US.UTF-8'
355    locale.getdefaultlocale()
356print('Preloading matplotlib to build fonts...')
357try:
358    import matplotlib
359except:
360    pass
361print('Checking python packages...')
362missing = []
363for pkg in ['numpy','scipy','matplotlib','wx','OpenGL',]:
364    try:
365        exec('import '+pkg)
366    except:
367        missing.append(pkg)
368
369if missing and not skipInstallChecks:
370    msg = """Sorry, this version of Python cannot be used
371for GSAS-II. It is missing the following package(s):
372\t"""
373    for pkg in missing: msg += " "+pkg
374    msg += "\nPlease install these package(s) and try running bootstrap.py again."
375    #print("Showing first error: ")
376    #for pkg in ['numpy','scipy','matplotlib','wx','OpenGL',]:
377    #    exec('import '+pkg)
378    BailOut(msg)
379
380if not skipDownloadSteps:
381    host = None
382    port = '80'
383    print('\nChecking for subversion...')
384    svn = whichsvn() # resets host & port if proxyinfo.txt is found
385    if not svn:
386        msg ="Sorry, subversion (svn) could not be found on your system."
387        msg += "\nPlease install this or place in path and rerun this."
388        BailOut(msg)
389    else:
390        print(' found svn image: '+svn)
391
392#if install_with_easyinstall:           
393#    print('\nInstalling PyOpenGL. Lots of warnings will follow... ')
394#    install_with_easyinstall('PyOpenGl')               
395#    print('done.')
396   
397print('Ready to bootstrap GSAS-II from repository\n\t'+g2home+'\nto '+path2GSAS2)
398proxycmds = []
399host,port,etc = getsvnProxy()
400if sys.version_info[0] == 2:
401    getinput = raw_input
402else:
403    getinput = input
404
405# get proxy setting from environment variable
406key = None
407for i in os.environ.keys():
408    if 'https_proxy' == i.lower():
409        key = i
410        break
411else:
412    for i in os.environ.keys():
413        if 'http_proxy' == i.lower():
414            key = i
415            break
416val = ''
417if key:
418    val = os.environ[key].strip()
419if val:
420    if val[-1] == '/':
421        val = val[:-1]
422    if len(val.split(':')) > 2:
423        host = ':'.join(val.split(':')[:-1])
424        port = val.split(':')[-1]
425    else:
426        host = ':'.join(val.split(':')[:-1])
427        port = val.split(':')[-1]
428
429# get proxy from user, if terminal available
430try:
431    if skipProxy:
432        host = ""
433    elif host:
434        print('\n'+75*'*')
435        ans = getinput("Enter the proxy address (type none to remove) ["+host+"]: ").strip()
436        if ans.lower() == "none": host = ""
437    else:
438        ans = getinput("Enter your proxy address [none needed]: ").strip()
439        if ans: host = ans
440    if host:
441        ans = getinput("Enter the proxy port ["+port+"]: ").strip()
442        if ans == "": ans=port
443        port = ans
444        print('If your site needs additional svn commands (such as \n\t',
445                  '--config-option servers:global:http-proxy-username=*account*','\n\t',
446                  '--config-option servers:global:http-proxy-password=*password*',
447                  '\nenter them now:')
448        if etc:
449            prevetc = ' '.join(etc)
450            print('\nDefault for next input is "{}"'.format(prevetc))
451            prompt = "Enter additional svn options (if any) [use previous]: "
452        else:
453            prompt = "Enter additional svn options (if any) [none]: "
454        ans = 'start'
455        etcstr = ''
456        while ans:
457            ans = getinput(prompt).strip()
458            prompt = "more svn options (if any): "
459            if etcstr: etcstr += ' '
460            etcstr += ans
461        if etcstr.strip():
462           etc = etcstr.split()
463except EOFError:
464    host = ""
465    port = ""
466    etc = []
467setsvnProxy(host,port,etc)
468# delete old proxy files
469localproxy = os.path.join(os.path.expanduser('~/.G2local/'),"proxyinfo.txt")
470for proxyinfo in localproxy,os.path.join(path2GSAS2,"proxyinfo.txt"):
471    if os.path.exists(proxyinfo):
472        try:
473            os.remove(proxyinfo)
474            print('Deleted file {}'.format(proxyinfo))
475        except:
476            pass
477if host:
478    try:
479        fp = open(proxyinfo,'w')
480    except:
481        fp = open(localproxy,'w')
482        proxyinfo = localproxy
483    try:
484        fp.write(host.strip()+'\n')
485        fp.write(port.strip()+'\n')
486        for i in etc:
487            if i.strip():
488                fp.write(i.strip()+'\n')
489        fp.close()
490        msg = 'Proxy info written: {} port {} etc {}\n'.format(host,port,etc)
491        print(msg)
492        fp = open(os.path.join(path2GSAS2,'bootstrap.log'),'a')
493        fp.write(msg)
494        fp.close()
495    except Exception as err:
496        print('Error writing file {}:\n{}'.format(proxyinfo,err))
497       
498if not skipDownloadSteps:
499    # patch: switch GSAS-II location if linked to XOR server (relocated May/June 2017)
500    cmd = [svn, 'info',path2GSAS2]
501    p = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
502    res,err = p.communicate()
503    if '.xor.' in str(res):
504        print('Switching previous install with .xor. download location to\n\thttps://subversion.xray.aps.anl.gov/pyGSAS')
505        cmd = [svn, 'switch','--relocate','https://subversion.xor.aps.anl.gov/pyGSAS',
506               'https://subversion.xray.aps.anl.gov/pyGSAS',path2GSAS2]
507        if proxycmds: cmd += proxycmds
508        p = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
509        res,err = p.communicate()
510        if err:
511            print('Please report this error to toby@anl.gov:')
512            print(err)
513            print(res)
514    # patch: switch GSAS-II location if switched to 2frame version (removed August 2017)
515    elif '2frame' in str(res):
516        print('Switching previous 2frame install to trunk\n\thttps://subversion.xray.aps.anl.gov/pyGSAS')
517        cmd = [svn, 'switch',g2home + '/trunk',path2GSAS2,
518               '--non-interactive','--trust-server-cert',
519               '--accept','theirs-conflict','--force','--ignore-ancestry']
520        if proxycmds: cmd += proxycmds
521        p = subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
522        res,err = p.communicate()
523        if err:
524            print('Please report this error to toby@anl.gov:')
525            print(err)
526            print(res)
527    elif 'not a working' not in str(res):
528        svncleanup(path2GSAS2)
529
530    print('\n'+75*'*')
531    print('Now preparing to install GSAS-II')
532    tryagain = True
533    err = False
534    firstPass = 0
535    while(tryagain):
536        tryagain = False
537        if err:
538            print('Retrying after a cleanup...')
539            svncleanup(path2GSAS2)
540        cmd = [svn, 'co', g2home+ 'trunk/', path2GSAS2, '--non-interactive', '--trust-server-cert']
541        if proxycmds: cmd += proxycmds
542        msg = 'svn load command: '
543        for item in cmd: msg += " "+item
544        print(msg)
545        s = subprocess.Popen(cmd,stderr=subprocess.PIPE)
546        print('\nsubversion output:')
547        out,err = MakeByte2str(s.communicate())
548        if 'Checksum' in err:  # deal with Checksum problem
549            err = svnChecksumPatch(svn,path2GSAS2,'-rHEAD')
550            if err:
551                print('error from svnChecksumPatch\n\t',err)
552        elif err:
553            print('subversion returned an error:')
554            print(out)
555            print(err)
556            if firstPass == 0: tryagain = True
557        firstPass += 1
558    if err:
559        print('Retrying with a command for older svn version...')
560        cmd = [svn, 'co', g2home+ 'trunk/', path2GSAS2]
561        if proxycmds: cmd += proxycmds
562        msg = ""
563        for item in cmd: msg += " " + item
564        print(msg)
565        s = subprocess.Popen(cmd,stderr=subprocess.PIPE)
566        out,err = MakeByte2str(s.communicate())
567        if err:
568            msg = 'subversion returned an error:\n'
569            msg += err
570            if os.path.exists(os.path.join(path2GSAS2,"makeBat.py")):
571                msg += '\nGSAS-II appears to be installed but failed to be updated. A likely reason'
572                msg += '\nis a network access problem. If your web browser works, but this update did'
573                msg += '\nnot, the most common reason is you need to use a network proxy. Please'
574                msg += '\ncheck with a network administrator or use http://www.whatismyproxy.com/'
575                msg += '\n\nIf installing from the gsas2full dist and your computer is not connected'
576                msg += '\nto the internet, this error message can be ignored.\n'
577            else:
578                # this will happen only with initial installs where all files
579                # are to be downloaded (not gsas2full or updates)
580                msg += '\n\n  *** GSAS-II failed to be installed. A likely reason is a network access'
581                msg += '\n  *** problem, most commonly because you need to use a network proxy. Please'
582                msg += '\n  *** check with a network administrator or use http://www.whatismyproxy.com/\n'
583            BailOut(msg)
584    print('\n'+75*'*')
585else:
586    svncleanup(path2GSAS2)
587
588# subsequent commands require GSASIIpath which better be here now, import it
589try:
590    import GSASIIpath
591    print('import of GSASIIpath completed')
592except Exception as err:
593    msg = 'Failed with import of GSASIIpath. This is unexpected.'
594    msg += '\nGSAS-II will not run without correcting this. Contact toby@anl.gov'
595    print('GSASIIpath import error\n')
596    print(err)
597    BailOut(msg)
598
599if skipDownloadSteps:
600    pass
601elif allBinaries:
602    print('Loading all binaries with command...')
603    if not GSASIIpath.svnSwitchDir('AllBinaries','',g2home+ 'Binaries/',None,True):
604        msg = 'Binary load failed. Subversion problem? Please seek help'
605        BailOut(msg)
606elif npVersion:
607    binaryVersion = GSASIIpath.GetBinaryPrefix(pyVersion)+'_n'+npVersion
608    print('Load binaries from '+binaryVersion)
609    if not GSASIIpath.svnSwitchDir('bindist','',g2home+ 'Binaries/'+binaryVersion,None,True):
610        msg = 'Binary load failed with '+binaryVersion+'. Subversion problem? Please seek help'
611        BailOut(msg)
612else:
613    print('Load binaries matching current python/numpy')
614    GSASIIpath.DownloadG2Binaries(g2home)
615       
616#===========================================================================
617# test if the compiled files load correctly
618#===========================================================================
619GSASIItested = False
620if not skipInstallChecks:
621    script = """ 
622# commands that test each module can at least be loaded & run something in pyspg
623try:
624    import GSASIIpath
625    GSASIIpath.SetBinaryPath(loadBinary=False)
626    import pyspg
627    import histogram2d
628    import polymask
629    import pypowder
630    import pytexture
631    pyspg.sgforpy('P -1')
632    print('==OK==')
633except Exception as err:
634    print(err)
635"""
636    p = subprocess.Popen([sys.executable,'-c',script],stdout=subprocess.PIPE,stderr=subprocess.PIPE,
637                         cwd=path2GSAS2)
638    res,err = MakeByte2str(p.communicate())
639    if '==OK==' not in str(res) or p.returncode != 0:
640        #print('\n'+75*'=')
641        msg = 'Failed when testing the GSAS-II compiled files. GSAS-II will not run'
642        msg += ' without correcting this.\n\nError message:\n'
643        if res: 
644            msg += res
645            msg += '\n'
646        if err:
647            msg += err
648        #print('\nAttempting to open a web page on compiling GSAS-II...')
649        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.)'
650        BailOut(msg)
651        #import webbrowser
652        #webbrowser.open_new('https://subversion.xray.aps.anl.gov/trac/pyGSAS/wiki/CompileGSASII')
653        #print(75*'=')
654    #    if '86' in platform.machine() and (sys.platform.startswith('linux')
655    #                                        or sys.platform == "darwin"
656    #                                        or sys.platform.startswith('win')):
657    #        print('Platform '+sys.platform+' with processor type '+platform.machine()+' is supported')
658    #    else:
659    #        print('Platform '+sys.platform+' with processor type '+platform.machine()+' not is supported')
660    else:
661        print('Successfully tested compiled routines')
662        GSASIItested = True
663#===========================================================================
664# import all .py files so that .pyc files get created
665if not skipInstallChecks:
666    print('Byte-compiling all .py files...')
667    import compileall
668    compileall.compile_dir(path2GSAS2,quiet=True)
669    print('done')
670#===========================================================================
671# do platform-dependent stuff
672#===========================================================================
673if sys.version_info[0] > 2:
674    def execfile(file):
675        with open(file) as source_file:
676            exec(source_file.read())
677
678#===========================================================================
679# on Windows, make a batch file with Python and GSAS-II location hard-coded
680if skipInstallChecks:
681    pass
682elif sys.platform.startswith('win') and os.path.exists(
683    os.path.join(path2GSAS2,"makeBat.py")):
684    execfile(os.path.join(path2GSAS2,"makeBat.py"))
685#===========================================================================
686# on a Mac, make an applescript
687elif sys.platform.startswith('darwin') and os.path.exists(
688         os.path.join(path2GSAS2,"makeMacApp.py")):
689    sys.argv = [os.path.join(path2GSAS2,"makeMacApp.py")]
690    print(u'running '+sys.argv[0])
691    execfile(sys.argv[0])
692#===========================================================================
693# On linux, make desktop icon
694elif sys.platform.startswith('linux') and os.path.exists(
695         os.path.join(path2GSAS2,"makeLinux.py")):
696    sys.argv = [os.path.join(path2GSAS2,"makeLinux.py")]
697    print(u'running '+sys.argv[0])
698    execfile(sys.argv[0])
699
Note: See TracBrowser for help on using the repository browser.