source: sasview/run.py @ 7df0ccd

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalcmagnetic_scattrelease-4.2.2ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since 7df0ccd was 7df0ccd, checked in by Paul Kienzle <pkienzle@…>, 7 years ago

Merge branch 'master' into ticket-887-reorg

  • Property mode set to 100755
File size: 5.6 KB
Line 
1# -*- coding: utf-8 -*-
2#!/usr/bin/env python
3"""
4Run sasview in place.  This allows sasview to use the python
5files in the source tree without having to call setup.py install
6first.  A rebuild is still necessary when working on sas models
7or c modules.
8
9Usage:
10
11./run.py [(module|script) args...]
12
13Without arguments run.py runs sasview.  With arguments, run.py will run
14the given module or script.
15"""
16from __future__ import print_function
17
18import imp
19import os
20import sys
21from contextlib import contextmanager
22from os.path import join as joinpath
23from os.path import abspath, dirname
24
25
26def addpath(path):
27    """
28    Add a directory to the python path environment, and to the PYTHONPATH
29    environment variable for subprocesses.
30    """
31    path = abspath(path)
32    if 'PYTHONPATH' in os.environ:
33        PYTHONPATH = path + os.pathsep + os.environ['PYTHONPATH']
34    else:
35        PYTHONPATH = path
36    os.environ['PYTHONPATH'] = PYTHONPATH
37    sys.path.insert(0, path)
38
39
40@contextmanager
41def cd(path):
42    """
43    Change directory for duration of "with" context.
44    """
45    old_dir = os.getcwd()
46    os.chdir(path)
47    yield
48    os.chdir(old_dir)
49
50
51def import_package(modname, path):
52    """Import a package into a particular point in the python namespace"""
53    #logger.debug("Dynamicly importing: %s", path)
54    mod = imp.load_source(modname, abspath(joinpath(path, '__init__.py')))
55    sys.modules[modname] = mod
56    mod.__path__ = [abspath(path)]
57    return mod
58
59
60def import_dll(modname, build_path):
61    """Import a DLL from the build directory"""
62    import sysconfig
63    ext = sysconfig.get_config_var('SO')
64    # build_path comes from context
65    path = joinpath(build_path, *modname.split('.')) + ext
66    # print "importing", modname, "from", path
67    return imp.load_dynamic(modname, path)
68
69
70def prepare():
71    # Don't create *.pyc files
72    sys.dont_write_bytecode = True
73
74    # Debug numpy warnings
75    #import numpy; numpy.seterr(all='raise')
76
77    # find the directories for the source and build
78    from distutils.util import get_platform
79    root = abspath(dirname(__file__))
80    platform = '%s-%s' % (get_platform(), sys.version[:3])
81    build_path = joinpath(root, 'build', 'lib.' + platform)
82
83    # Notify the help menu that the Sphinx documentation is in a different
84    # place than it otherwise would be.
85    os.environ['SASVIEW_DOC_PATH'] = joinpath(build_path, "doc")
86
87    # Make sure that we have a private version of mplconfig
88    #mplconfig = joinpath(abspath(dirname(__file__)), '.mplconfig')
89    #os.environ['MPLCONFIGDIR'] = mplconfig
90    #if not os.path.exists(mplconfig): os.mkdir(mplconfig)
91    #import matplotlib
92    # matplotlib.use('Agg')
93    # print matplotlib.__file__
94    #import pylab; pylab.hold(False)
95    # add periodictable to the path
96    try:
97        import periodictable
98    except:
99        addpath(joinpath(root, '..', 'periodictable'))
100
101    try:
102        import bumps
103    except:
104        addpath(joinpath(root, '..', 'bumps'))
105
106    # select wx version
107    #addpath(os.path.join(root, '..','wxPython-src-3.0.0.0','wxPython'))
108
109    # Build project if the build directory does not already exist.
110    if not os.path.exists(build_path):
111        import subprocess
112        with cd(root):
113            subprocess.call((sys.executable, "setup.py", "build"), shell=False)
114
115    # Put the source trees on the path
116    addpath(joinpath(root, 'src'))
117
118    # sasmodels on the path
119    addpath(joinpath(root, '../sasmodels/'))
120
121    # The sas.models package Compiled Model files should be pulled in from the build directory even though
122    # the source is stored in src/sas/models.
123
124    # Compiled modules need to be pulled from the build directory.
125    # Some packages are not where they are needed, so load them explicitly.
126    import sas.sascalc.pr
127    sas.sascalc.pr.core = import_package('sas.sascalc.pr.core',
128                                         joinpath(build_path, 'sas', 'sascalc', 'pr', 'core'))
129
130    # Compiled modules need to be pulled from the build directory.
131    # Some packages are not where they are needed, so load them explicitly.
132    import sas.sascalc.file_converter
133    sas.sascalc.file_converter.core = import_package('sas.sascalc.file_converter.core',
134                                                     joinpath(build_path, 'sas', 'sascalc', 'file_converter', 'core'))
135
136    import sas.sascalc.calculator
137    sas.sascalc.calculator.core = import_package('sas.sascalc.calculator.core',
138                                                 joinpath(build_path, 'sas', 'sascalc', 'calculator', 'core'))
139
140    sys.path.append(build_path)
141
142    set_git_tag()
143    # print "\n".join(sys.path)
144
145def set_git_tag():
146    try:
147        import subprocess
148        import os
149        import platform
150        FNULL = open(os.devnull, 'w')
151        if platform.system() == "Windows":
152            args = ['git', 'describe', '--tags']
153        else:
154            args = ['git describe --tags']
155        git_revision = subprocess.check_output(args, stderr=FNULL, shell=True)
156        import sas.sasview
157        sas.sasview.__build__ = str(git_revision).strip()
158    except subprocess.CalledProcessError as cpe:
159        logger.warning("Error while determining build number\n  Using command:\n %s \n Output:\n %s"% (cpe.cmd,cpe.output))
160
161
162if __name__ == "__main__":
163    # Need to add absolute path before actual prepare call,
164    # so logging can be done during initialization process too
165    root = abspath(dirname(__file__))
166    addpath(joinpath(root, 'src'))
167    from sas.logger_config import SetupLogger
168    logger = SetupLogger(__name__).config_development()
169
170    logger.debug("Starting SASVIEW in debug mode.")
171    prepare()
172    from sas.sasview.sasview import run_gui
173    run_gui()
174    logger.debug("Ending SASVIEW in debug mode.")
Note: See TracBrowser for help on using the repository browser.