~ubuntu-branches/debian/experimental/spyder/experimental

« back to all changes in this revision

Viewing changes to spyderlib/widgets/externalshell/sitecustomize.py

  • Committer: Package Import Robot
  • Author(s): Picca Frédéric-Emmanuel
  • Date: 2014-05-29 09:06:26 UTC
  • mfrom: (1.1.21) (18.1.6 sid)
  • Revision ID: package-import@ubuntu.com-20140529090626-f58t82g0n5iewaxu
Tags: 2.3.0~rc+dfsg-1~experimental2
* Add spyder-common binary package for all the python2,3 common files
* debian/path
  - 0001-fix-documentation-installation.patch (deleted)
  + 0001-fix-spyderlib-path.patch (new)

Show diffs side-by-side

added added

removed removed

Lines of Context:
6
6
import os.path as osp
7
7
import pdb
8
8
import bdb
9
 
import __builtin__
10
 
 
 
9
 
 
10
 
 
11
# sys.argv can be missing when Python is embedded, taking care of it.
 
12
# Fixes Issue 1473 and other crazy crashes with IPython 0.13 trying to
 
13
# access it.
 
14
if not hasattr(sys, 'argv'):
 
15
    sys.argv = ['']
 
16
 
 
17
#==============================================================================
 
18
# Important Note:
 
19
#
 
20
# We avoid importing spyderlib here, so we are handling Python 3 compatiblity
 
21
# by hand.
 
22
#==============================================================================
 
23
def _print(*objects, **options):
 
24
    end = options.get('end', '\n')
 
25
    file = options.get('file', sys.stdout)
 
26
    sep = options.get('sep', ' ')
 
27
    string = sep.join([str(obj) for obj in objects])
 
28
    if sys.version[0] == '3':
 
29
        # Python 3
 
30
        local_dict = {}
 
31
        exec('printf = print', local_dict) # to avoid syntax error in Python 2
 
32
        local_dict['printf'](string, file=file, end=end, sep=sep)
 
33
    else:
 
34
        # Python 2
 
35
        if end:
 
36
            print >>file, string
 
37
        else:
 
38
            print >>file, string,
 
39
 
 
40
try:
 
41
    import __builtin__ as builtins
 
42
except ImportError:
 
43
    # Python 3
 
44
    import builtins
 
45
    basestring = (str,)
 
46
    def execfile(filename, namespace):
 
47
        # Open a source file correctly, whatever its encoding is
 
48
        exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace)
11
49
 
12
50
# Colorization of sys.stderr (standard Python interpreter)
13
51
if os.environ.get("COLORIZE_SYS_STDERR", "").lower() == "true":
89
127
 
90
128
 
91
129
# For our MacOs X app
92
 
mac_and_epd = False    # Are we on Mac and using EPD?
93
130
if sys.platform == 'darwin' and 'Spyder.app' in __file__:
94
131
    interpreter = os.environ.get('SPYDER_INTERPRETER')
95
132
    if 'Spyder.app' not in interpreter:
98
135
        # now we are removing it
99
136
        del os.environ['PYTHONPATH']
100
137
 
101
 
        # Add the App's main python path at the end of sys.path
 
138
        # Add a minimal library (with spyderlib) at the end of sys.path to
 
139
        # be able to connect our monitor to the external console
102
140
        app_pythonpath = 'Spyder.app/Contents/Resources/lib/python2.7'
103
 
        full_pythonpath = filter(lambda p: p.endswith(app_pythonpath),
104
 
                                 sys.path)
 
141
        full_pythonpath = [p for p in sys.path if p.endswith(app_pythonpath)]
105
142
        if full_pythonpath:
106
143
            sys.path.remove(full_pythonpath[0])
107
 
            sys.path.append(full_pythonpath[0])
108
 
 
109
 
        # Set QT_API manually when the interpreter is EPD, to avoid
110
 
        # an ugly traceback with our scientific_startup script
111
 
        if 'EPD' in interpreter:
112
 
            mac_and_epd = True
113
 
            os.environ['QT_API'] = 'pyside'
 
144
            sys.path.append(full_pythonpath[0] + osp.sep + 'minimal-lib')
114
145
    else:
115
146
        # Add missing variables and methods to the app's site module
116
147
        import site
126
157
if mpl_backend:
127
158
    try:
128
159
        import matplotlib
129
 
        if mac_and_epd:
130
 
            # Just for precaution, since mpl is not working with PySide
131
 
            # inside Qt apps, because of its lack of an input hook
132
 
            matplotlib.rcParams['backend.qt4'] = 'PySide'
 
160
        if os.environ.get('QT_API') == 'pyside':
 
161
            # Try to address PySide lack of an input hook on Mac by settting
 
162
            # mpl_backend to always be MacOSX
 
163
            # Fixes Issue 347
 
164
            if mpl_backend == 'Qt4Agg' and sys.platform == 'darwin':
 
165
                mpl_backend = 'MacOSX'
 
166
        matplotlib.rcParams['docstring.hardcopy'] = True
133
167
        matplotlib.use(mpl_backend)
134
168
    except ImportError:
135
169
        pass
144
178
 
145
179
 
146
180
# Set standard outputs encoding:
147
 
# (otherwise, for example, print u"é" will fail)
 
181
# (otherwise, for example, print("é") will fail)
148
182
encoding = None
149
183
try:
150
184
    import locale
158
192
if encoding is None:
159
193
    encoding = "UTF-8"
160
194
 
161
 
sys.setdefaultencoding(encoding)
162
 
os.environ['SPYDER_ENCODING'] = encoding
 
195
try:
 
196
    sys.setdefaultencoding(encoding)
 
197
    os.environ['SPYDER_ENCODING'] = encoding
 
198
except AttributeError:
 
199
    # Python 3
 
200
    pass
163
201
    
164
202
try:
165
203
    import sitecustomize  #analysis:ignore
195
233
            try:
196
234
                source = source.__file__
197
235
            except AttributeError:
198
 
                print >>sys.stderr, "The argument must be either a string"\
199
 
                                    "or a module object"
 
236
                raise ValueError("source argument must be either "
 
237
                                 "a string or a module object")
200
238
        if source.endswith('.pyc'):
201
239
            source = source[:-1]
202
240
        source = osp.abspath(source)
203
241
        if osp.exists(source):
204
242
            monitor.notify_open_file(source, lineno=lineno)
205
243
        else:
206
 
            print >>sys.stderr, "Can't open file %s" % source
207
 
    __builtin__.open_in_spyder = open_in_spyder
 
244
            _print("Can't open file %s" % source, file=sys.stderr)
 
245
    builtins.open_in_spyder = open_in_spyder
208
246
    
209
247
    # * PyQt4:
210
248
    #   * Removing PyQt4 input hook which is not working well on Windows since 
289
327
 
290
328
if os.environ.get("IPYTHON_KERNEL", "").lower() == "true":
291
329
 
292
 
    #XXX If Matplotlib is not imported first, the IPython import will fail
 
330
    #XXX If Matplotlib is not imported first, the next IPython import will fail
293
331
    try:
294
332
        import matplotlib  # analysis:ignore
295
333
    except ImportError:
298
336
    from IPython.core.debugger import Pdb as ipyPdb
299
337
    pdb.Pdb = ipyPdb
300
338
 
 
339
    # Patch unittest.main so that errors are printed directly in the console.
 
340
    # See http://comments.gmane.org/gmane.comp.python.ipython.devel/10557
 
341
    # Fixes Issue 1370
 
342
    import unittest
 
343
    from unittest import TestProgram
 
344
    class IPyTesProgram(TestProgram):
 
345
        def __init__(self, *args, **kwargs):
 
346
            test_runner = unittest.TextTestRunner(stream=sys.stderr)
 
347
            kwargs['testRunner'] = kwargs.pop('testRunner', test_runner)
 
348
            kwargs['exit'] = False
 
349
            TestProgram.__init__(self, *args, **kwargs)
 
350
 
 
351
    unittest.main = IPyTesProgram
 
352
 
301
353
class SpyderPdb(pdb.Pdb):
302
354
    def set_spyder_breakpoints(self):
303
355
        self.clear_all_breaks()
314
366
        if CONF.get('run', 'breakpoints/enabled', True):
315
367
            breakpoints = CONF.get('run', 'breakpoints', {})
316
368
            i = 0
317
 
            for fname, data in breakpoints.iteritems():
 
369
            for fname, data in list(breakpoints.items()):
318
370
                for linenumber, condition in data:
319
371
                    i += 1
320
372
                    self.set_break(self.canonic(fname), linenumber,
353
405
        if old_func is not None:
354
406
            # Add the old func to a list of old funcs.
355
407
            old_ref = "_old_%s_%s" % (patch_name, fname)
356
 
            #print old_ref, old_func
 
408
            #print(old_ref, old_func)
357
409
            old_attr = getattr(cls, old_ref, None)
358
410
            if old_attr is None:
359
411
                setattr(cls, old_ref, old_func)
418
470
        def patched_setapi(name, no):
419
471
            try:
420
472
                original_setapi(name, no)
421
 
            except ValueError, msg:
422
 
                print >>sys.stderr, "Warning/PyQt4-Spyder (%s)" % str(msg)
 
473
            except ValueError as msg:
 
474
                _print("Warning/PyQt4-Spyder (%s)" % str(msg), file=sys.stderr)
423
475
        sip.setapi = patched_setapi
424
476
    except ImportError:
425
477
        pass
442
494
        if pathlist is None:
443
495
            pathlist = []
444
496
        self.pathlist = pathlist
445
 
        self.previous_modules = sys.modules.keys()
 
497
        self.previous_modules = list(sys.modules.keys())
446
498
 
447
499
    def is_module_blacklisted(self, modname, modpath):
448
500
        for path in [sys.prefix]+self.pathlist:
460
512
        Do not del C modules
461
513
        """
462
514
        log = []
463
 
        for modname, module in sys.modules.items():
 
515
        for modname, module in list(sys.modules.items()):
464
516
            if modname not in self.previous_modules:
465
517
                modpath = getattr(module, '__file__', None)
466
518
                if modpath is None:
472
524
                    log.append(modname)
473
525
                    del sys.modules[modname]
474
526
        if verbose and log:
475
 
            print "\x1b[4;33m%s\x1b[24m%s\x1b[0m"\
476
 
                  % ("UMD has deleted", ": "+", ".join(log))
 
527
            _print("\x1b[4;33m%s\x1b[24m%s\x1b[0m"\
 
528
                   % ("UMD has deleted", ": "+", ".join(log)))
477
529
 
478
530
__umd__ = None
479
531
 
499
551
    """
500
552
    try:
501
553
        filename = filename.decode('utf-8')
502
 
    except (UnicodeError, TypeError):
 
554
    except (UnicodeError, TypeError, AttributeError):
 
555
        # UnicodeError, TypeError --> eventually raised in Python 2
 
556
        # AttributeError --> systematically raised in Python 3
503
557
        pass
504
558
    global __umd__
505
559
    if os.environ.get("UMD_ENABLED", "").lower() == "true":
523
577
    if wdir is not None:
524
578
        try:
525
579
            wdir = wdir.decode('utf-8')
526
 
        except (UnicodeError, TypeError):
 
580
        except (UnicodeError, TypeError, AttributeError):
 
581
            # UnicodeError, TypeError --> eventually raised in Python 2
 
582
            # AttributeError --> systematically raised in Python 3
527
583
            pass
528
584
        os.chdir(wdir)
529
585
    execfile(filename, namespace)
530
586
    sys.argv = ['']
531
587
    namespace.pop('__file__')
532
588
    
533
 
__builtin__.runfile = runfile
 
589
builtins.runfile = runfile
534
590
 
535
591
 
536
592
def debugfile(filename, args=None, wdir=None):
544
600
    debugger._wait_for_mainpyfile = 1
545
601
    debugger.mainpyfile = filename
546
602
    debugger._user_requested_quit = 0
 
603
    if os.name == 'nt':
 
604
        filename = filename.replace('\\', '/')
547
605
    debugger.run("runfile(%r, args=%r, wdir=%r)" % (filename, args, wdir))
548
606
 
549
 
__builtin__.debugfile = debugfile
 
607
builtins.debugfile = debugfile
550
608
 
551
609
 
552
610
def evalsc(command):
562
620
        else:
563
621
            from subprocess import Popen, PIPE
564
622
            Popen(command, shell=True, stdin=PIPE)
565
 
            print '\n'
 
623
            _print('\n')
566
624
    else:
567
625
        # General command
568
626
        namespace = _get_globals()
579
637
                except KeyError:
580
638
                    pass
581
639
        elif command in ('cd', 'pwd'):
582
 
            print os.getcwdu()
 
640
            try:
 
641
                _print(os.getcwdu())
 
642
            except AttributeError:
 
643
                _print(os.getcwd())
583
644
        elif command == 'ls':
584
645
            if os.name == 'nt':
585
646
                evalsc('!dir')
589
650
            from spyderlib import baseconfig
590
651
            execfile(baseconfig.SCIENTIFIC_STARTUP, namespace)
591
652
        else:
592
 
            raise NotImplementedError, "Unsupported command: '%s'" % command
 
653
            raise NotImplementedError("Unsupported command: '%s'" % command)
593
654
 
594
 
__builtin__.evalsc = evalsc
 
655
builtins.evalsc = evalsc
595
656
 
596
657
 
597
658
# Restoring original PYTHONPATH