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

Last change on this file since 4747 was 4747, checked in by toby, 9 months ago

more work on install for OSX

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