source: sasview/src/sas/sasview/sasview.py @ 899e084

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

build console app as well as gui

  • Property mode set to 100644
File size: 6.9 KB
Line 
1"""
2Base module for loading and running the main SasView application.
3"""
4################################################################################
5#This software was developed by the University of Tennessee as part of the
6#Distributed Data Analysis of Neutron Scattering Experiments (DANSE)
7#project funded by the US National Science Foundation.
8#
9#See the license text in license.txt
10#
11#copyright 2009, University of Tennessee
12################################################################################
13import os
14import sys
15import logging
16import traceback
17
18
19reload(sys)
20sys.setdefaultencoding("iso-8859-1")
21
22
23class StreamToLogger(object):
24    """
25        File-like stream object that redirects writes to a logger instance.
26    """
27    def __init__(self, logger, log_level=logging.INFO):
28        self.logger = logger
29        self.log_level = log_level
30        self.linebuf = ''
31
32    def write(self, buf):
33        """
34        Main logging method
35        """
36        # Write the message to stdout so we can see it when running interactively
37        sys.stdout.write(buf)
38        for line in buf.rstrip().splitlines():
39            self.logger.log(self.log_level, line.rstrip())
40
41PLUGIN_MODEL_DIR = 'plugin_models'
42APP_NAME = 'SasView'
43
44class SasView():
45    """
46    Main class for running the SasView application
47    """
48    def __init__(self):
49        """
50        """
51        from sas.sasgui.guiframe.gui_manager import SasViewApp
52        self.gui = SasViewApp(0)
53        # Set the application manager for the GUI
54        self.gui.set_manager(self)
55        # Add perspectives to the basic application
56        # Additional perspectives can still be loaded
57        # dynamically
58        # Note: py2exe can't find dynamically loaded
59        # modules. We load the fitting module here
60        # to ensure a complete Windows executable build.
61
62        # Fitting perspective
63        try:
64            import sas.sasgui.perspectives.fitting as module
65            fitting_plug = module.Plugin()
66            self.gui.add_perspective(fitting_plug)
67        except Exception:
68            logging.error("%s: could not find Fitting plug-in module"% APP_NAME)
69            logging.error(traceback.format_exc())
70
71        # P(r) perspective
72        try:
73            import sas.sasgui.perspectives.pr as module
74            pr_plug = module.Plugin()
75            self.gui.add_perspective(pr_plug)
76        except:
77            logging.error("%s: could not find P(r) plug-in module"% APP_NAME)
78            logging.error(traceback.format_exc())
79
80        #Invariant perspective
81        try:
82            import sas.sasgui.perspectives.invariant as module
83            invariant_plug = module.Plugin()
84            self.gui.add_perspective(invariant_plug)
85        except Exception as e :
86            logging.error("%s: could not find Invariant plug-in module"% \
87                          APP_NAME)
88            logging.error(traceback.format_exc())
89
90        #Calculator perspective
91        try:
92            import sas.sasgui.perspectives.calculator as module
93            calculator_plug = module.Plugin()
94            self.gui.add_perspective(calculator_plug)
95        except:
96            logging.error("%s: could not find Calculator plug-in module"% \
97                                                        APP_NAME)
98            logging.error(traceback.format_exc())
99
100
101        # Add welcome page
102        from .welcome_panel import WelcomePanel
103        self.gui.set_welcome_panel(WelcomePanel)
104
105        # Build the GUI
106        self.gui.build_gui()
107        # delete unused model folder
108        self.gui.clean_plugin_models(PLUGIN_MODEL_DIR)
109        # Start the main loop
110        self.gui.MainLoop()
111
112
113def setup_logging():
114    log_file = os.path.join(os.path.expanduser("~"), 'sasview.log')
115    logging.basicConfig(level=logging.INFO,
116                        format='%(asctime)s %(levelname)s %(message)s',
117                        filename=log_file,
118                        )
119    logging.captureWarnings(True)
120
121    stderr_logger = logging.getLogger('STDERR')
122    sl = StreamToLogger(stderr_logger, logging.ERROR)
123    sys.stderr = sl
124
125    # Log the start of the session
126    logging.info(" --- SasView session started ---")
127
128    # Log the python version
129    logging.info("Python: %s" % sys.version)
130
131
132def setup_wx():
133    # Allow the dynamic selection of wxPython via an environment variable, when devs
134    # who have multiple versions of the module installed want to pick between them.
135    # This variable does not have to be set of course, and through normal usage will
136    # probably not be, but this can make things a little easier when upgrading to a
137    # new version of wx.
138    WX_ENV_VAR = "SASVIEW_WX_VERSION"
139    if WX_ENV_VAR in os.environ:
140        logging.info("You have set the %s environment variable to %s." % \
141                     (WX_ENV_VAR, os.environ[WX_ENV_VAR]))
142        import wxversion
143        if wxversion.checkInstalled(os.environ[WX_ENV_VAR]):
144            logging.info("Version %s of wxPython is installed, so using that version." % os.environ[WX_ENV_VAR])
145            wxversion.select(os.environ[WX_ENV_VAR])
146        else:
147            logging.error("Version %s of wxPython is not installed, so using default version." % os.environ[WX_ENV_VAR])
148    else:
149        logging.info("You have not set the %s environment variable, so using default version of wxPython." % WX_ENV_VAR)
150
151    import wx
152
153    try:
154        logging.info("Wx version: %s" % wx.__version__)
155    except:
156        logging.error("Wx version: error reading version")
157
158    from . import wxcruft
159    wxcruft.call_later_fix()
160    #wxcruft.trace_new_id()
161    #Always use private .matplotlib setup to avoid conflicts with other
162    #uses of matplotlib
163
164
165def setup_mpl():
166    import sas.sasgui
167    mplconfigdir = os.path.join(sas.sasgui.get_user_dir(), '.matplotlib')
168    if not os.path.exists(mplconfigdir):
169        os.mkdir(mplconfigdir)
170    os.environ['MPLCONFIGDIR'] = mplconfigdir
171    # Set backend to WXAgg; this overrides matplotlibrc, but shouldn't override
172    # mpl.use().  Note: Don't import matplotlib here since the script that
173    # we are running may not actually need it; also, putting as little on the
174    # path as we can
175    os.environ['MPLBACKEND'] = 'WXAgg'
176
177
178def run_gui():
179    """
180    __main__ method for loading and running SasView
181    """
182    from multiprocessing import freeze_support
183    freeze_support()
184    setup_logging()
185    setup_wx()
186    setup_mpl()
187    SasView()
188
189
190def run_cli():
191    setup_mpl()
192    if len(sys.argv) == 1:
193        # Run sasview as an interactive python interpreter
194        sys.argv = ["ipython", "--pylab"]
195        from IPython import start_ipython
196        sys.exit(start_ipython())
197    else:
198        # Run sasview as a python script interpreter
199        thing_to_run = sys.argv[1]
200        sys.argv = sys.argv[1:]
201        import runpy
202        if os.path.exists(thing_to_run):
203            runpy.run_path(thing_to_run, run_name="__main__")
204        else:
205            runpy.run_module(thing_to_run, run_name="__main__")
206
207if __name__ == "__main__":
208    run_gui()
209
Note: See TracBrowser for help on using the repository browser.