source: sasview/run.py @ 0dde203

ticket-1249
Last change on this file since 0dde203 was 952ea1f, checked in by Paul Kienzle <pkienzle@…>, 6 years ago

move c extensions from core/module.so to _module.so

  • Property mode set to 100755
File size: 5.3 KB
Line 
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
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
25def addpath(path):
26    """
27    Add a directory to the python path environment, and to the PYTHONPATH
28    environment variable for subprocesses.
29    """
30    path = abspath(path)
31    if 'PYTHONPATH' in os.environ:
32        PYTHONPATH = path + os.pathsep + os.environ['PYTHONPATH']
33    else:
34        PYTHONPATH = path
35    os.environ['PYTHONPATH'] = PYTHONPATH
36    sys.path.insert(0, path)
37
38
39@contextmanager
40def cd(path):
41    """
42    Change directory for duration of "with" context.
43    """
44    old_dir = os.getcwd()
45    os.chdir(path)
46    yield
47    os.chdir(old_dir)
48
49
50def import_package(modname, path):
51    """Import a package into a particular point in the python namespace"""
52    #logger.debug("Dynamicly importing: %s", path)
53    mod = imp.load_source(modname, abspath(joinpath(path, '__init__.py')))
54    sys.modules[modname] = mod
55    mod.__path__ = [abspath(path)]
56    return mod
57
58
59def import_dll(modname, build_path):
60    """Import a DLL from the build directory"""
61    import sysconfig
62    ext = sysconfig.get_config_var('SO')
63    # build_path comes from context
64    path = joinpath(build_path, *modname.split('.')) + ext
65    # print "importing", modname, "from", path
66    return imp.load_dynamic(modname, path)
67
68
69def prepare(rebuild=True):
70    # Don't create *.pyc files
71    sys.dont_write_bytecode = True
72
73    # Debug numpy warnings
74    #import numpy; numpy.seterr(all='raise')
75
76    # find the directories for the source and build
77    from distutils.util import get_platform
78    root = abspath(dirname(__file__))
79    platform = '%s-%s' % (get_platform(), sys.version[:3])
80    build_path = joinpath(root, 'build', 'lib.' + platform)
81
82    # Notify the help menu that the Sphinx documentation is in a different
83    # place than it otherwise would be.
84    os.environ['SASVIEW_DOC_PATH'] = joinpath(build_path, "doc")
85
86    # Make sure that we have a private version of mplconfig
87    #mplconfig = joinpath(abspath(dirname(__file__)), '.mplconfig')
88    #os.environ['MPLCONFIGDIR'] = mplconfig
89    #if not os.path.exists(mplconfig): os.mkdir(mplconfig)
90    #import matplotlib
91    # matplotlib.use('Agg')
92    # print matplotlib.__file__
93    #import pylab; pylab.hold(False)
94    # add periodictable to the path
95    try:
96        import periodictable
97    except ImportError:
98        addpath(joinpath(root, '..', 'periodictable'))
99
100    try:
101        import bumps
102    except ImportError:
103        addpath(joinpath(root, '..', 'bumps'))
104
105    try:
106        import tinycc
107    except ImportError:
108        addpath(joinpath(root, '../tinycc/build/lib'))
109
110    # select wx version
111    #addpath(os.path.join(root, '..','wxPython-src-3.0.0.0','wxPython'))
112
113    # Put the sas source tree on the path
114    addpath(joinpath(root, 'src'))
115
116    # Put sasmodels on the path
117    addpath(joinpath(root, '../sasmodels/'))
118
119    # Check if the C extensions are already built
120    try:
121        from sas.sascalc.pr import _pr_inversion
122        from sas.sascalc.calculator import _sld2i
123        from sas.sascalc.file_converter import _bsl_loader
124    except ImportError:
125        rebuild = True
126
127    # Build C extensions if necessary.  Do an inplace build to simplify path.
128    if rebuild:
129        import subprocess
130        build_cmd = [sys.executable, "setup.py", "build_ext", "--inplace", "update"]
131        if os.name == 'nt':
132            build_cmd.append('--compiler=tinycc')
133        # need shell=True on windows to keep console box from popping up
134        shell = (os.name == 'nt')
135        with cd(root):
136            subprocess.call(build_cmd, shell=shell)
137
138    set_git_tag()
139    # print "\n".join(sys.path)
140
141def set_git_tag():
142    try:
143        import subprocess
144        import os
145        import platform
146        FNULL = open(os.devnull, 'w')
147        if platform.system() == "Windows":
148            args = ['git', 'describe', '--tags']
149        else:
150            args = ['git describe --tags']
151        git_revision = subprocess.check_output(args, stderr=FNULL, shell=True)
152        import sas.sasview
153        sas.sasview.__build__ = str(git_revision).strip()
154    except subprocess.CalledProcessError as cpe:
155        get_logger().warning("Error while determining build number\n  Using command:\n %s \n Output:\n %s"% (cpe.cmd,cpe.output))
156
157_logger = None
158def get_logger():
159    global _logger
160    if _logger is None:
161        from sas.logger_config import SetupLogger
162        _logger = SetupLogger(__name__).config_development()
163    return _logger
164
165if __name__ == "__main__":
166    # Need to add absolute path before actual prepare call,
167    # so logging can be done during initialization process too
168    root = abspath(dirname(__file__))
169    addpath(joinpath(root, 'src'))
170
171    get_logger().debug("Starting SASVIEW in debug mode.")
172    prepare()
173    from sas.sasview.sasview import run_cli, run_gui
174    if len(sys.argv) == 1:
175        run_gui()
176    else:
177        run_cli()
178    get_logger().debug("Ending SASVIEW in debug mode.")
Note: See TracBrowser for help on using the repository browser.