source: sasview/run.py @ 7c64911

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 7c64911 was 7c64911, checked in by Paul Kienzle <pkienzle@…>, 7 years ago

make logger available to run.py functions even when not run as main

  • Property mode set to 100755
File size: 5.7 KB
RevLine 
[7fb59b2]1# -*- coding: utf-8 -*-
[a3e5455]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
[3a39c2e]6first.  A rebuild is still necessary when working on sas models
[a3e5455]7or c modules.
8
9Usage:
10
[6fe5100]11./run.py [(module|script) args...]
12
13Without arguments run.py runs sasview.  With arguments, run.py will run
14the given module or script.
[a3e5455]15"""
[c6bdb3b]16from __future__ import print_function
[a3e5455]17
18import imp
19import os
20import sys
[bbd97e5]21from contextlib import contextmanager
[38beeab]22from os.path import join as joinpath
23from os.path import abspath, dirname
[a3e5455]24
25def addpath(path):
26    """
27    Add a directory to the python path environment, and to the PYTHONPATH
28    environment variable for subprocesses.
29    """
[bbd97e5]30    path = abspath(path)
[a3e5455]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
[f36e01f]38
[a3e5455]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
[f36e01f]49
[a3e5455]50def import_package(modname, path):
51    """Import a package into a particular point in the python namespace"""
[f94a935]52    #logger.debug("Dynamicly importing: %s", path)
[f36e01f]53    mod = imp.load_source(modname, abspath(joinpath(path, '__init__.py')))
[a3e5455]54    sys.modules[modname] = mod
[bbd97e5]55    mod.__path__ = [abspath(path)]
[a3e5455]56    return mod
57
[f36e01f]58
[499639c]59def import_dll(modname, build_path):
[a3e5455]60    """Import a DLL from the build directory"""
[499639c]61    import sysconfig
62    ext = sysconfig.get_config_var('SO')
[a3e5455]63    # build_path comes from context
[f36e01f]64    path = joinpath(build_path, *modname.split('.')) + ext
65    # print "importing", modname, "from", path
[a3e5455]66    return imp.load_dynamic(modname, path)
67
[f36e01f]68
[bbd97e5]69def prepare():
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__))
[f36e01f]79    platform = '%s-%s' % (get_platform(), sys.version[:3])
80    build_path = joinpath(root, 'build', 'lib.' + platform)
[18e7309]81
82    # Notify the help menu that the Sphinx documentation is in a different
[70a9d1c]83    # place than it otherwise would be.
[c3437260]84    os.environ['SASVIEW_DOC_PATH'] = joinpath(build_path, "doc")
85
[bbd97e5]86    # Make sure that we have a private version of mplconfig
[278e86f]87    #mplconfig = joinpath(abspath(dirname(__file__)), '.mplconfig')
88    #os.environ['MPLCONFIGDIR'] = mplconfig
89    #if not os.path.exists(mplconfig): os.mkdir(mplconfig)
[bbd97e5]90    #import matplotlib
[f36e01f]91    # matplotlib.use('Agg')
92    # print matplotlib.__file__
[bbd97e5]93    #import pylab; pylab.hold(False)
94    # add periodictable to the path
[f36e01f]95    try:
96        import periodictable
97    except:
98        addpath(joinpath(root, '..', 'periodictable'))
[bbd97e5]99
[f36e01f]100    try:
101        import bumps
102    except:
103        addpath(joinpath(root, '..', 'bumps'))
[95d58d3]104
[bbd97e5]105    # select wx version
106    #addpath(os.path.join(root, '..','wxPython-src-3.0.0.0','wxPython'))
107
108    # Build project if the build directory does not already exist.
109    if not os.path.exists(build_path):
110        import subprocess
111        with cd(root):
112            subprocess.call((sys.executable, "setup.py", "build"), shell=False)
113
114    # Put the source trees on the path
115    addpath(joinpath(root, 'src'))
116
[0e4e554]117    # sasmodels on the path
118    addpath(joinpath(root, '../sasmodels/'))
119
[3a39c2e]120    # The sas.models package Compiled Model files should be pulled in from the build directory even though
121    # the source is stored in src/sas/models.
[bbd97e5]122
123    # Compiled modules need to be pulled from the build directory.
124    # Some packages are not where they are needed, so load them explicitly.
[b699768]125    import sas.sascalc.pr
126    sas.sascalc.pr.core = import_package('sas.sascalc.pr.core',
[f36e01f]127                                         joinpath(build_path, 'sas', 'sascalc', 'pr', 'core'))
[bbd97e5]128
[9e531f2]129    # Compiled modules need to be pulled from the build directory.
130    # Some packages are not where they are needed, so load them explicitly.
[18e7309]131    import sas.sascalc.file_converter
132    sas.sascalc.file_converter.core = import_package('sas.sascalc.file_converter.core',
[f36e01f]133                                                     joinpath(build_path, 'sas', 'sascalc', 'file_converter', 'core'))
[bbd97e5]134
[9e531f2]135    import sas.sascalc.calculator
136    sas.sascalc.calculator.core = import_package('sas.sascalc.calculator.core',
[f36e01f]137                                                 joinpath(build_path, 'sas', 'sascalc', 'calculator', 'core'))
[bbd97e5]138
139    sys.path.append(build_path)
140
[7c105e8]141    set_git_tag()
[f36e01f]142    # print "\n".join(sys.path)
143
[7c105e8]144def set_git_tag():
145    try:
146        import subprocess
147        import os
148        import platform
149        FNULL = open(os.devnull, 'w')
150        if platform.system() == "Windows":
151            args = ['git', 'describe', '--tags']
152        else:
153            args = ['git describe --tags']
154        git_revision = subprocess.check_output(args, stderr=FNULL, shell=True)
155        import sas.sasview
156        sas.sasview.__build__ = str(git_revision).strip()
157    except subprocess.CalledProcessError as cpe:
[e61f668]158        get_logger().warning("Error while determining build number\n  Using command:\n %s \n Output:\n %s"% (cpe.cmd,cpe.output))
[7c105e8]159
[e61f668]160_logger = None
161def get_logger():
162    global _logger
[7c64911]163    if _logger is None:
[e61f668]164        from sas.logger_config import SetupLogger
165        _logger = SetupLogger(__name__).config_development()
166    return _logger
[bbd97e5]167
168if __name__ == "__main__":
[f36e01f]169    # Need to add absolute path before actual prepare call,
170    # so logging can be done during initialization process too
[d9df833]171    root = abspath(dirname(__file__))
[ed03b99]172    addpath(joinpath(root, 'src'))
[d9df833]173
[e61f668]174    get_logger().debug("Starting SASVIEW in debug mode.")
[bbd97e5]175    prepare()
[899e084]176    from sas.sasview.sasview import run_gui
177    run_gui()
[e61f668]178    get_logger().debug("Ending SASVIEW in debug mode.")
Note: See TracBrowser for help on using the repository browser.