6
6
import os.path as osp
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
14
if not hasattr(sys, 'argv'):
17
#==============================================================================
20
# We avoid importing spyderlib here, so we are handling Python 3 compatiblity
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':
31
exec('printf = print', local_dict) # to avoid syntax error in Python 2
32
local_dict['printf'](string, file=file, end=end, sep=sep)
41
import __builtin__ as builtins
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)
12
50
# Colorization of sys.stderr (standard Python interpreter)
13
51
if os.environ.get("COLORIZE_SYS_STDERR", "").lower() == "true":
98
135
# now we are removing it
99
136
del os.environ['PYTHONPATH']
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),
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])
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:
113
os.environ['QT_API'] = 'pyside'
144
sys.path.append(full_pythonpath[0] + osp.sep + 'minimal-lib')
115
146
# Add missing variables and methods to the app's site module
128
159
import matplotlib
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
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:
146
180
# Set standard outputs encoding:
147
# (otherwise, for example, print u"é" will fail)
181
# (otherwise, for example, print("é") will fail)
158
192
if encoding is None:
159
193
encoding = "UTF-8"
161
sys.setdefaultencoding(encoding)
162
os.environ['SPYDER_ENCODING'] = encoding
196
sys.setdefaultencoding(encoding)
197
os.environ['SPYDER_ENCODING'] = encoding
198
except AttributeError:
165
203
import sitecustomize #analysis:ignore
196
234
source = source.__file__
197
235
except AttributeError:
198
print >>sys.stderr, "The argument must be either a string"\
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)
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
210
248
# * Removing PyQt4 input hook which is not working well on Windows since
290
328
if os.environ.get("IPYTHON_KERNEL", "").lower() == "true":
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
294
332
import matplotlib # analysis:ignore
295
333
except ImportError:
298
336
from IPython.core.debugger import Pdb as ipyPdb
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
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)
351
unittest.main = IPyTesProgram
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', {})
317
for fname, data in breakpoints.iteritems():
369
for fname, data in list(breakpoints.items()):
318
370
for linenumber, condition in data:
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):
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:
442
494
if pathlist is None:
444
496
self.pathlist = pathlist
445
self.previous_modules = sys.modules.keys()
497
self.previous_modules = list(sys.modules.keys())
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
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)))
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
505
559
if os.environ.get("UMD_ENABLED", "").lower() == "true":
523
577
if wdir is not None:
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
529
585
execfile(filename, namespace)
531
587
namespace.pop('__file__')
533
__builtin__.runfile = runfile
589
builtins.runfile = runfile
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
604
filename = filename.replace('\\', '/')
547
605
debugger.run("runfile(%r, args=%r, wdir=%r)" % (filename, args, wdir))
549
__builtin__.debugfile = debugfile
607
builtins.debugfile = debugfile
552
610
def evalsc(command):
589
650
from spyderlib import baseconfig
590
651
execfile(baseconfig.SCIENTIFIC_STARTUP, namespace)
592
raise NotImplementedError, "Unsupported command: '%s'" % command
653
raise NotImplementedError("Unsupported command: '%s'" % command)
594
__builtin__.evalsc = evalsc
655
builtins.evalsc = evalsc
597
658
# Restoring original PYTHONPATH