File: __init__.py

package info (click to toggle)
python-astropy 1.3-8~bpo8%2B2
  • links: PTS, VCS
  • area: main
  • in suites: jessie-backports
  • size: 44,292 kB
  • sloc: ansic: 160,360; python: 137,322; sh: 11,493; lex: 7,638; yacc: 4,956; xml: 1,796; makefile: 474; cpp: 364
file content (339 lines) | stat: -rw-r--r-- 10,943 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Astropy is a package intended to contain core functionality and some
common tools needed for performing astronomy and astrophysics research with
Python. It also provides an index for other astronomy packages and tools for
managing them.
"""

from __future__ import absolute_import

import sys
import os
from warnings import warn

if sys.version_info[:2] < (2, 7):
    warn("Astropy does not support Python 2.6 (in v1.2 and later)")


def _is_astropy_source(path=None):
    """
    Returns whether the source for this module is directly in an astropy
    source distribution or checkout.
    """

    # If this __init__.py file is in ./astropy/ then import is within a source
    # dir .astropy-root is a file distributed with the source, but that should
    # not installed
    if path is None:
        path = os.path.join(os.path.dirname(__file__), os.pardir)
    elif os.path.isfile(path):
        path = os.path.dirname(path)

    source_dir = os.path.abspath(path)
    return os.path.exists(os.path.join(source_dir, '.astropy-root'))


def _is_astropy_setup():
    """
    Returns whether we are currently being imported in the context of running
    Astropy's setup.py.
    """

    main_mod = sys.modules.get('__main__')
    if not main_mod:
        return False

    return (getattr(main_mod, '__file__', False) and
            os.path.basename(main_mod.__file__).rstrip('co') == 'setup.py' and
            _is_astropy_source(main_mod.__file__))


# this indicates whether or not we are in astropy's setup.py
try:
    _ASTROPY_SETUP_
except NameError:
    from sys import version_info
    if version_info[0] >= 3:
        import builtins
    else:
        import __builtin__ as builtins

    # This will set the _ASTROPY_SETUP_ to True by default if
    # we are running Astropy's setup.py
    builtins._ASTROPY_SETUP_ = _is_astropy_setup()


try:
    from .version import version as __version__
except ImportError:
    # TODO: Issue a warning using the logging framework
    __version__ = ''
try:
    from .version import githash as __githash__
except ImportError:
    # TODO: Issue a warning using the logging framework
    __githash__ = ''


__minimum_numpy_version__ = '1.7.0'


# The location of the online documentation for astropy
# This location will normally point to the current released version of astropy
if 'dev' in __version__:
    online_docs_root = 'http://docs.astropy.org/en/latest/'
else:
    online_docs_root = 'http://docs.astropy.org/en/{0}/'.format(__version__)


def _check_numpy():
    """
    Check that Numpy is installed and it is of the minimum version we
    require.
    """
    # Note: We could have used distutils.version for this comparison,
    # but it seems like overkill to import distutils at runtime.
    requirement_met = False

    try:
        import numpy
    except ImportError:
        pass
    else:
        from .utils import minversion
        requirement_met = minversion(numpy, __minimum_numpy_version__)

    if not requirement_met:
        msg = ("Numpy version {0} or later must be installed to use "
               "Astropy".format(__minimum_numpy_version__))
        raise ImportError(msg)

    return numpy


if not _ASTROPY_SETUP_:
    _check_numpy()


from . import config as _config

class Conf(_config.ConfigNamespace):
    """
    Configuration parameters for `astropy`.
    """

    unicode_output = _config.ConfigItem(
        False,
        'When True, use Unicode characters when outputting values, and '
        'displaying widgets at the console.')
    use_color = _config.ConfigItem(
        sys.platform != 'win32',
        'When True, use ANSI color escape sequences when writing to the console.',
        aliases=['astropy.utils.console.USE_COLOR', 'astropy.logger.USE_COLOR'])
    max_lines = _config.ConfigItem(
        None,
        description='Maximum number of lines in the display of pretty-printed '
        'objects. If not provided, try to determine automatically from the '
        'terminal size.  Negative numbers mean no limit.',
        cfgtype='integer(default=None)',
        aliases=['astropy.table.pprint.max_lines'])
    max_width = _config.ConfigItem(
        None,
        description='Maximum number of characters per line in the display of '
        'pretty-printed objects.  If not provided, try to determine '
        'automatically from the terminal size. Negative numbers mean no '
        'limit.',
        cfgtype='integer(default=None)',
        aliases=['astropy.table.pprint.max_width'])

conf = Conf()

# Create the test() function
from .tests.runner import TestRunner
test = TestRunner.make_test_runner_in(__path__[0])


# if we are *not* in setup mode, import the logger and possibly populate the
# configuration file with the defaults
def _initialize_astropy():
    from . import config

    def _rollback_import(message):
        log.error(message)
        # Now disable exception logging to avoid an annoying error in the
        # exception logger before we raise the import error:
        _teardown_log()

        # Roll back any astropy sub-modules that have been imported thus
        # far

        for key in list(sys.modules):
            if key.startswith('astropy.'):
                del sys.modules[key]
        raise ImportError('astropy')

    try:
        from .utils import _compiler
    except ImportError:
        if _is_astropy_source():
            log.warning('You appear to be trying to import astropy from '
                        'within a source checkout without building the '
                        'extension modules first.  Attempting to (re)build '
                        'extension modules:')

            try:
                _rebuild_extensions()
            except BaseException as exc:
                _rollback_import(
                    'An error occurred while attempting to rebuild the '
                    'extension modules.  Please try manually running '
                    '`./setup.py develop` or `./setup.py build_ext '
                    '--inplace` to see what the issue was.  Extension '
                    'modules must be successfully compiled and importable '
                    'in order to import astropy.')
                # Reraise the Exception only in case it wasn't an Exception,
                # for example if a "SystemExit" or "KeyboardInterrupt" was
                # invoked.
                if not isinstance(exc, Exception):
                    raise

        else:
            # Outright broken installation; don't be nice.
            raise

    # add these here so we only need to cleanup the namespace at the end
    config_dir = os.path.dirname(__file__)

    try:
        config.configuration.update_default_config(__package__, config_dir)
    except config.configuration.ConfigurationDefaultMissingError as e:
        wmsg = (e.args[0] + " Cannot install default profile. If you are "
                "importing from source, this is expected.")
        warn(config.configuration.ConfigurationDefaultMissingWarning(wmsg))


def _rebuild_extensions():
    global __version__
    global __githash__

    import subprocess
    import time

    from .utils.console import Spinner
    from .extern.six import next

    devnull = open(os.devnull, 'w')
    old_cwd = os.getcwd()
    os.chdir(os.path.join(os.path.dirname(__file__), os.pardir))
    try:
        sp = subprocess.Popen([sys.executable, 'setup.py', 'build_ext',
                               '--inplace'], stdout=devnull,
                               stderr=devnull)
        with Spinner('Rebuilding extension modules') as spinner:
            while sp.poll() is None:
                next(spinner)
                time.sleep(0.05)
    finally:
        os.chdir(old_cwd)
        devnull.close()

    if sp.returncode != 0:
        raise OSError('Running setup.py build_ext --inplace failed '
                      'with error code {0}: try rerunning this command '
                      'manually to check what the error was.'.format(
                          sp.returncode))

    # Try re-loading module-level globals from the astropy.version module,
    # which may not have existed before this function ran
    try:
        from .version import version as __version__
    except ImportError:
        pass

    try:
        from .version import githash as __githash__
    except ImportError:
        pass


# Set the bibtex entry to the article referenced in CITATION
def _get_bibtex():
    import re
    if os.path.exists('CITATION'):
        with open('CITATION', 'r') as citation:
            refs = re.findall(r'\{[^()]*\}', citation.read())
            if len(refs) == 0: return ''
            bibtexreference = "@ARTICLE{0}".format(refs[0])
        return bibtexreference
    else:
        return ''

__bibtex__ = _get_bibtex()


import logging

# Use the root logger as a dummy log before initilizing Astropy's logger
log = logging.getLogger()


if not _ASTROPY_SETUP_:
    from .logger import _init_log, _teardown_log

    log = _init_log()

    _initialize_astropy()

    from .utils.misc import find_api_page


def online_help(query):
    """
    Search the online Astropy documentation for the given query.
    Opens the results in the default web browser.  Requires an active
    Internet connection.

    Parameters
    ----------
    query : str
        The search query.
    """
    from .extern.six.moves.urllib.parse import urlencode
    import webbrowser

    version = __version__
    if 'dev' in version:
        version = 'latest'
    else:
        version = 'v' + version

    url = 'http://docs.astropy.org/en/{0}/search.html?{1}'.format(
        version, urlencode({'q': query}))

    webbrowser.open(url)


__dir__ = ['__version__', '__githash__', '__minimum_numpy_version__',
           '__bibtex__', 'test', 'log', 'find_api_page', 'online_help',
           'online_docs_root', 'conf']


from types import ModuleType as __module_type__
# Clean up top-level namespace--delete everything that isn't in __dir__
# or is a magic attribute, and that isn't a submodule of this package
for varname in dir():
    if not ((varname.startswith('__') and varname.endswith('__')) or
            varname in __dir__ or
            (varname[0] != '_' and
                isinstance(locals()[varname], __module_type__) and
                locals()[varname].__name__.startswith(__name__ + '.'))):
        # The last clause in the the above disjunction deserves explanation:
        # When using relative imports like ``from .. import config``, the
        # ``config`` variable is automatically created in the namespace of
        # whatever module ``..`` resolves to (in this case astropy).  This
        # happens a few times just in the module setup above.  This allows
        # the cleanup to keep any public submodules of the astropy package
        del locals()[varname]

del varname, __module_type__