forked from ipython/ipython
-
Notifications
You must be signed in to change notification settings - Fork 4
/
iplib.py
2873 lines (2339 loc) · 108 KB
/
iplib.py
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
IPython -- An enhanced Interactive Python
Requires Python 2.4 or newer.
This file contains all the classes and helper functions specific to IPython.
"""
#*****************************************************************************
# Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
# Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#
# Note: this code originally subclassed code.InteractiveConsole from the
# Python standard library. Over time, all of that class has been copied
# verbatim here for modifications which could not be accomplished by
# subclassing. At this point, there are no dependencies at all on the code
# module anymore (it is not even imported). The Python License (sec. 2)
# allows for this, but it's always nice to acknowledge credit where credit is
# due.
#*****************************************************************************
#****************************************************************************
# Modules and globals
# Python standard modules
import __main__
import __builtin__
import StringIO
import bdb
import cPickle as pickle
import codeop
import exceptions
import glob
import inspect
import keyword
import new
import os
import pydoc
import re
import shutil
import string
import sys
import tempfile
import traceback
import types
from pprint import pprint, pformat
# IPython's own modules
#import IPython
from IPython import Debugger,OInspect,PyColorize,ultraTB
from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
from IPython.Extensions import pickleshare
from IPython.FakeModule import FakeModule, init_fakemod_dict
from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
from IPython.Logger import Logger
from IPython.Magic import Magic
from IPython.Prompts import CachedOutput
from IPython.ipstruct import Struct
from IPython.background_jobs import BackgroundJobManager
from IPython.usage import cmd_line_usage,interactive_usage
from IPython.genutils import *
from IPython.strdispatch import StrDispatch
import IPython.ipapi
import IPython.history
import IPython.prefilter as prefilter
import IPython.shadowns
# Globals
# store the builtin raw_input globally, and use this always, in case user code
# overwrites it (like wx.py.PyShell does)
raw_input_original = raw_input
# compiled regexps for autoindent management
dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
#****************************************************************************
# Some utility function definitions
ini_spaces_re = re.compile(r'^(\s+)')
def num_ini_spaces(strng):
"""Return the number of initial spaces in a string"""
ini_spaces = ini_spaces_re.match(strng)
if ini_spaces:
return ini_spaces.end()
else:
return 0
def softspace(file, newvalue):
"""Copied from code.py, to remove the dependency"""
oldvalue = 0
try:
oldvalue = file.softspace
except AttributeError:
pass
try:
file.softspace = newvalue
except (AttributeError, TypeError):
# "attribute-less object" or "read-only attributes"
pass
return oldvalue
def user_setup(ipythondir,rc_suffix,mode='install',interactive=True):
"""Install or upgrade the user configuration directory.
Can be called when running for the first time or to upgrade the user's
.ipython/ directory.
Parameters
----------
ipythondir : path
The directory to be used for installation/upgrade. In 'install' mode,
if this path already exists, the function exits immediately.
rc_suffix : str
Extension for the config files. On *nix platforms it is typically the
empty string, while Windows normally uses '.ini'.
mode : str, optional
Valid modes are 'install' and 'upgrade'.
interactive : bool, optional
If False, do not wait for user input on any errors. Normally after
printing its status information, this function waits for the user to
hit Return before proceeding. This is because the default use case is
when first installing the IPython configuration, so we want the user to
acknowledge the initial message, which contains some useful
information.
"""
# For automatic use, deactivate all i/o
if interactive:
def wait():
try:
raw_input("Please press <RETURN> to start IPython.")
except EOFError:
print >> Term.cout
print '*'*70
def printf(s):
print s
else:
wait = lambda : None
printf = lambda s : None
# Install mode should be re-entrant: if the install dir already exists,
# bail out cleanly.
# XXX. This is too hasty to return. We need to check to make sure that
# all the expected config files and directories are actually there. We
# currently have a failure mode if someone deletes a needed config file
# but still has the ipythondir.
if mode == 'install' and os.path.isdir(ipythondir):
return
cwd = os.getcwd() # remember where we started
glb = glob.glob
printf('*'*70)
if mode == 'install':
printf(
"""Welcome to IPython. I will try to create a personal configuration directory
where you can customize many aspects of IPython's functionality in:\n""")
else:
printf('I am going to upgrade your configuration in:')
printf(ipythondir)
rcdirend = os.path.join('IPython','UserConfig')
cfg = lambda d: os.path.join(d,rcdirend)
try:
rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
printf("Initializing from configuration: %s" % rcdir)
except IndexError:
warning = """
Installation error. IPython's directory was not found.
Check the following:
The ipython/IPython directory should be in a directory belonging to your
PYTHONPATH environment variable (that is, it should be in a directory
belonging to sys.path). You can copy it explicitly there or just link to it.
IPython will create a minimal default configuration for you.
"""
warn(warning)
wait()
if sys.platform =='win32':
inif = 'ipythonrc.ini'
else:
inif = 'ipythonrc'
minimal_setup = {'ipy_user_conf.py' : 'import ipy_defaults',
inif : '# intentionally left blank' }
os.makedirs(ipythondir, mode = 0777)
for f, cont in minimal_setup.items():
# In 2.5, this can be more cleanly done using 'with'
fobj = file(ipythondir + '/' + f,'w')
fobj.write(cont)
fobj.close()
return
if mode == 'install':
try:
shutil.copytree(rcdir,ipythondir)
os.chdir(ipythondir)
rc_files = glb("ipythonrc*")
for rc_file in rc_files:
os.rename(rc_file,rc_file+rc_suffix)
except:
warning = """
There was a problem with the installation:
%s
Try to correct it or contact the developers if you think it's a bug.
IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
warn(warning)
wait()
return
elif mode == 'upgrade':
try:
os.chdir(ipythondir)
except:
printf("""
Can not upgrade: changing to directory %s failed. Details:
%s
""" % (ipythondir,sys.exc_info()[1]) )
wait()
return
else:
sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
for new_full_path in sources:
new_filename = os.path.basename(new_full_path)
if new_filename.startswith('ipythonrc'):
new_filename = new_filename + rc_suffix
# The config directory should only contain files, skip any
# directories which may be there (like CVS)
if os.path.isdir(new_full_path):
continue
if os.path.exists(new_filename):
old_file = new_filename+'.old'
if os.path.exists(old_file):
os.remove(old_file)
os.rename(new_filename,old_file)
shutil.copy(new_full_path,new_filename)
else:
raise ValueError('unrecognized mode for install: %r' % mode)
# Fix line-endings to those native to each platform in the config
# directory.
try:
os.chdir(ipythondir)
except:
printf("""
Problem: changing to directory %s failed.
Details:
%s
Some configuration files may have incorrect line endings. This should not
cause any problems during execution. """ % (ipythondir,sys.exc_info()[1]) )
wait()
else:
for fname in glb('ipythonrc*'):
try:
native_line_ends(fname,backup=0)
except IOError:
pass
if mode == 'install':
printf("""
Successful installation!
Please read the sections 'Initial Configuration' and 'Quick Tips' in the
IPython manual (there are both HTML and PDF versions supplied with the
distribution) to make sure that your system environment is properly configured
to take advantage of IPython's features.
Important note: the configuration system has changed! The old system is
still in place, but its setting may be partly overridden by the settings in
"~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
if some of the new settings bother you.
""")
else:
printf("""
Successful upgrade!
All files in your directory:
%(ipythondir)s
which would have been overwritten by the upgrade were backed up with a .old
extension. If you had made particular customizations in those files you may
want to merge them back into the new files.""" % locals() )
wait()
os.chdir(cwd)
#****************************************************************************
# Local use exceptions
class SpaceInInput(exceptions.Exception): pass
#****************************************************************************
# Local use classes
class Bunch: pass
class Undefined: pass
class Quitter(object):
"""Simple class to handle exit, similar to Python 2.5's.
It handles exiting in an ipython-safe manner, which the one in Python 2.5
doesn't do (obviously, since it doesn't know about ipython)."""
def __init__(self,shell,name):
self.shell = shell
self.name = name
def __repr__(self):
return 'Type %s() to exit.' % self.name
__str__ = __repr__
def __call__(self):
self.shell.exit()
class InputList(list):
"""Class to store user input.
It's basically a list, but slices return a string instead of a list, thus
allowing things like (assuming 'In' is an instance):
exec In[4:7]
or
exec In[5:9] + In[14] + In[21:25]"""
def __getslice__(self,i,j):
return ''.join(list.__getslice__(self,i,j))
class SyntaxTB(ultraTB.ListTB):
"""Extension which holds some state: the last exception value"""
def __init__(self,color_scheme = 'NoColor'):
ultraTB.ListTB.__init__(self,color_scheme)
self.last_syntax_error = None
def __call__(self, etype, value, elist):
self.last_syntax_error = value
ultraTB.ListTB.__call__(self,etype,value,elist)
def clear_err_state(self):
"""Return the current error state and clear it"""
e = self.last_syntax_error
self.last_syntax_error = None
return e
#****************************************************************************
# Main IPython class
# FIXME: the Magic class is a mixin for now, and will unfortunately remain so
# until a full rewrite is made. I've cleaned all cross-class uses of
# attributes and methods, but too much user code out there relies on the
# equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
#
# But at least now, all the pieces have been separated and we could, in
# principle, stop using the mixin. This will ease the transition to the
# chainsaw branch.
# For reference, the following is the list of 'self.foo' uses in the Magic
# class as of 2005-12-28. These are names we CAN'T use in the main ipython
# class, to prevent clashes.
# ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
# 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
# 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
# 'self.value']
class InteractiveShell(object,Magic):
"""An enhanced console for Python."""
# class attribute to indicate whether the class supports threads or not.
# Subclasses with thread support should override this as needed.
isthreaded = False
def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
user_ns=None,user_global_ns=None,banner2='',
custom_exceptions=((),None),embedded=False):
# log system
self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
# Job manager (for jobs run as background threads)
self.jobs = BackgroundJobManager()
# Store the actual shell's name
self.name = name
self.more = False
# We need to know whether the instance is meant for embedding, since
# global/local namespaces need to be handled differently in that case
self.embedded = embedded
if embedded:
# Control variable so users can, from within the embedded instance,
# permanently deactivate it.
self.embedded_active = True
# command compiler
self.compile = codeop.CommandCompiler()
# User input buffer
self.buffer = []
# Default name given in compilation of code
self.filename = '<ipython console>'
# Install our own quitter instead of the builtins. For python2.3-2.4,
# this brings in behavior like 2.5, and for 2.5 it's identical.
__builtin__.exit = Quitter(self,'exit')
__builtin__.quit = Quitter(self,'quit')
# Make an empty namespace, which extension writers can rely on both
# existing and NEVER being used by ipython itself. This gives them a
# convenient location for storing additional information and state
# their extensions may require, without fear of collisions with other
# ipython names that may develop later.
self.meta = Struct()
# Create the namespace where the user will operate. user_ns is
# normally the only one used, and it is passed to the exec calls as
# the locals argument. But we do carry a user_global_ns namespace
# given as the exec 'globals' argument, This is useful in embedding
# situations where the ipython shell opens in a context where the
# distinction between locals and globals is meaningful. For
# non-embedded contexts, it is just the same object as the user_ns dict.
# FIXME. For some strange reason, __builtins__ is showing up at user
# level as a dict instead of a module. This is a manual fix, but I
# should really track down where the problem is coming from. Alex
# Schmolck reported this problem first.
# A useful post by Alex Martelli on this topic:
# Re: inconsistent value from __builtins__
# Von: Alex Martelli <aleaxit@yahoo.com>
# Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
# Gruppen: comp.lang.python
# Michael Hohn <hohn@hooknose.lbl.gov> wrote:
# > >>> print type(builtin_check.get_global_binding('__builtins__'))
# > <type 'dict'>
# > >>> print type(__builtins__)
# > <type 'module'>
# > Is this difference in return value intentional?
# Well, it's documented that '__builtins__' can be either a dictionary
# or a module, and it's been that way for a long time. Whether it's
# intentional (or sensible), I don't know. In any case, the idea is
# that if you need to access the built-in namespace directly, you
# should start with "import __builtin__" (note, no 's') which will
# definitely give you a module. Yeah, it's somewhat confusing:-(.
# These routines return properly built dicts as needed by the rest of
# the code, and can also be used by extension writers to generate
# properly initialized namespaces.
user_ns, user_global_ns = IPython.ipapi.make_user_namespaces(user_ns,
user_global_ns)
# Assign namespaces
# This is the namespace where all normal user variables live
self.user_ns = user_ns
self.user_global_ns = user_global_ns
# An auxiliary namespace that checks what parts of the user_ns were
# loaded at startup, so we can list later only variables defined in
# actual interactive use. Since it is always a subset of user_ns, it
# doesn't need to be seaparately tracked in the ns_table
self.user_config_ns = {}
# A namespace to keep track of internal data structures to prevent
# them from cluttering user-visible stuff. Will be updated later
self.internal_ns = {}
# Namespace of system aliases. Each entry in the alias
# table must be a 2-tuple of the form (N,name), where N is the number
# of positional arguments of the alias.
self.alias_table = {}
# Now that FakeModule produces a real module, we've run into a nasty
# problem: after script execution (via %run), the module where the user
# code ran is deleted. Now that this object is a true module (needed
# so docetst and other tools work correctly), the Python module
# teardown mechanism runs over it, and sets to None every variable
# present in that module. Top-level references to objects from the
# script survive, because the user_ns is updated with them. However,
# calling functions defined in the script that use other things from
# the script will fail, because the function's closure had references
# to the original objects, which are now all None. So we must protect
# these modules from deletion by keeping a cache.
#
# To avoid keeping stale modules around (we only need the one from the
# last run), we use a dict keyed with the full path to the script, so
# only the last version of the module is held in the cache. Note,
# however, that we must cache the module *namespace contents* (their
# __dict__). Because if we try to cache the actual modules, old ones
# (uncached) could be destroyed while still holding references (such as
# those held by GUI objects that tend to be long-lived)>
#
# The %reset command will flush this cache. See the cache_main_mod()
# and clear_main_mod_cache() methods for details on use.
# This is the cache used for 'main' namespaces
self._main_ns_cache = {}
# And this is the single instance of FakeModule whose __dict__ we keep
# copying and clearing for reuse on each %run
self._user_main_module = FakeModule()
# A table holding all the namespaces IPython deals with, so that
# introspection facilities can search easily.
self.ns_table = {'user':user_ns,
'user_global':user_global_ns,
'alias':self.alias_table,
'internal':self.internal_ns,
'builtin':__builtin__.__dict__
}
# Similarly, track all namespaces where references can be held and that
# we can safely clear (so it can NOT include builtin). This one can be
# a simple list.
self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns,
self.alias_table, self.internal_ns,
self._main_ns_cache ]
# We need to insert into sys.modules something that looks like a
# module but which accesses the IPython namespace, for shelve and
# pickle to work interactively. Normally they rely on getting
# everything out of __main__, but for embedding purposes each IPython
# instance has its own private namespace, so we can't go shoving
# everything into __main__.
# note, however, that we should only do this for non-embedded
# ipythons, which really mimic the __main__.__dict__ with their own
# namespace. Embedded instances, on the other hand, should not do
# this because they need to manage the user local/global namespaces
# only, but they live within a 'normal' __main__ (meaning, they
# shouldn't overtake the execution environment of the script they're
# embedded in).
if not embedded:
try:
main_name = self.user_ns['__name__']
except KeyError:
raise KeyError,'user_ns dictionary MUST have a "__name__" key'
else:
#print "pickle hack in place" # dbg
#print 'main_name:',main_name # dbg
sys.modules[main_name] = FakeModule(self.user_ns)
# List of input with multi-line handling.
self.input_hist = InputList()
# This one will hold the 'raw' input history, without any
# pre-processing. This will allow users to retrieve the input just as
# it was exactly typed in by the user, with %hist -r.
self.input_hist_raw = InputList()
# list of visited directories
try:
self.dir_hist = [os.getcwd()]
except OSError:
self.dir_hist = []
# dict of output history
self.output_hist = {}
# Get system encoding at startup time. Certain terminals (like Emacs
# under Win32 have it set to None, and we need to have a known valid
# encoding to use in the raw_input() method
try:
self.stdin_encoding = sys.stdin.encoding or 'ascii'
except AttributeError:
self.stdin_encoding = 'ascii'
# dict of things NOT to alias (keywords, builtins and some magics)
no_alias = {}
no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
for key in keyword.kwlist + no_alias_magics:
no_alias[key] = 1
no_alias.update(__builtin__.__dict__)
self.no_alias = no_alias
# Object variable to store code object waiting execution. This is
# used mainly by the multithreaded shells, but it can come in handy in
# other situations. No need to use a Queue here, since it's a single
# item which gets cleared once run.
self.code_to_run = None
# escapes for automatic behavior on the command line
self.ESC_SHELL = '!'
self.ESC_SH_CAP = '!!'
self.ESC_HELP = '?'
self.ESC_MAGIC = '%'
self.ESC_QUOTE = ','
self.ESC_QUOTE2 = ';'
self.ESC_PAREN = '/'
# And their associated handlers
self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
self.ESC_QUOTE : self.handle_auto,
self.ESC_QUOTE2 : self.handle_auto,
self.ESC_MAGIC : self.handle_magic,
self.ESC_HELP : self.handle_help,
self.ESC_SHELL : self.handle_shell_escape,
self.ESC_SH_CAP : self.handle_shell_escape,
}
# class initializations
Magic.__init__(self,self)
# Python source parser/formatter for syntax highlighting
pyformat = PyColorize.Parser().format
self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
# hooks holds pointers used for user-side customizations
self.hooks = Struct()
self.strdispatchers = {}
# Set all default hooks, defined in the IPython.hooks module.
hooks = IPython.hooks
for hook_name in hooks.__all__:
# default hooks have priority 100, i.e. low; user hooks should have
# 0-100 priority
self.set_hook(hook_name,getattr(hooks,hook_name), 100)
#print "bound hook",hook_name
# Flag to mark unconditional exit
self.exit_now = False
self.usage_min = """\
An enhanced console for Python.
Some of its features are:
- Readline support if the readline library is present.
- Tab completion in the local namespace.
- Logging of input, see command-line options.
- System shell escape via ! , eg !ls.
- Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
- Keeps track of locally defined variables via %who, %whos.
- Show object information with a ? eg ?x or x? (use ?? for more info).
"""
if usage: self.usage = usage
else: self.usage = self.usage_min
# Storage
self.rc = rc # This will hold all configuration information
self.pager = 'less'
# temporary files used for various purposes. Deleted at exit.
self.tempfiles = []
# Keep track of readline usage (later set by init_readline)
self.has_readline = False
# template for logfile headers. It gets resolved at runtime by the
# logstart method.
self.loghead_tpl = \
"""#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
#log# DO NOT CHANGE THIS LINE OR THE TWO BELOW -* coding: %s *-
#log# opts = %s
#log# args = %s
#log# It is safe to make manual edits below here.
#log#-----------------------------------------------------------------------
"""
# for pushd/popd management
try:
self.home_dir = get_home_dir()
except HomeDirError,msg:
fatal(msg)
self.dir_stack = []
# Functions to call the underlying shell.
# The first is similar to os.system, but it doesn't return a value,
# and it allows interpolation of variables in the user's namespace.
self.system = lambda cmd: \
self.hooks.shell_hook(self.var_expand(cmd,depth=2))
# These are for getoutput and getoutputerror:
self.getoutput = lambda cmd: \
getoutput(self.var_expand(cmd,depth=2),
header=self.rc.system_header,
verbose=self.rc.system_verbose)
self.getoutputerror = lambda cmd: \
getoutputerror(self.var_expand(cmd,depth=2),
header=self.rc.system_header,
verbose=self.rc.system_verbose)
# keep track of where we started running (mainly for crash post-mortem)
self.starting_dir = os.getcwd()
# Various switches which can be set
self.CACHELENGTH = 5000 # this is cheap, it's just text
self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
self.banner2 = banner2
# TraceBack handlers:
# Syntax error handler.
self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
# The interactive one is initialized with an offset, meaning we always
# want to remove the topmost item in the traceback, which is our own
# internal code. Valid modes: ['Plain','Context','Verbose']
self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
color_scheme='NoColor',
tb_offset = 1)
# IPython itself shouldn't crash. This will produce a detailed
# post-mortem if it does. But we only install the crash handler for
# non-threaded shells, the threaded ones use a normal verbose reporter
# and lose the crash handler. This is because exceptions in the main
# thread (such as in GUI code) propagate directly to sys.excepthook,
# and there's no point in printing crash dumps for every user exception.
if self.isthreaded:
ipCrashHandler = ultraTB.FormattedTB()
else:
from IPython import CrashHandler
ipCrashHandler = CrashHandler.IPythonCrashHandler(self)
self.set_crash_handler(ipCrashHandler)
# and add any custom exception handlers the user may have specified
self.set_custom_exc(*custom_exceptions)
# indentation management
self.autoindent = False
self.indent_current_nsp = 0
# Make some aliases automatically
# Prepare list of shell aliases to auto-define
if os.name == 'posix':
auto_alias = ('mkdir mkdir', 'rmdir rmdir',
'mv mv -i','rm rm -i','cp cp -i',
'cat cat','less less','clear clear',
# a better ls
'ls ls -F',
# long ls
'll ls -lF')
# Extra ls aliases with color, which need special treatment on BSD
# variants
ls_extra = ( # color ls
'lc ls -F -o --color',
# ls normal files only
'lf ls -F -o --color %l | grep ^-',
# ls symbolic links
'lk ls -F -o --color %l | grep ^l',
# directories or links to directories,
'ldir ls -F -o --color %l | grep /$',
# things which are executable
'lx ls -F -o --color %l | grep ^-..x',
)
# The BSDs don't ship GNU ls, so they don't understand the
# --color switch out of the box
if 'bsd' in sys.platform:
ls_extra = ( # ls normal files only
'lf ls -lF | grep ^-',
# ls symbolic links
'lk ls -lF | grep ^l',
# directories or links to directories,
'ldir ls -lF | grep /$',
# things which are executable
'lx ls -lF | grep ^-..x',
)
auto_alias = auto_alias + ls_extra
elif os.name in ['nt','dos']:
auto_alias = ('ls dir /on',
'ddir dir /ad /on', 'ldir dir /ad /on',
'mkdir mkdir','rmdir rmdir','echo echo',
'ren ren','cls cls','copy copy')
else:
auto_alias = ()
self.auto_alias = [s.split(None,1) for s in auto_alias]
# Produce a public API instance
self.api = IPython.ipapi.IPApi(self)
# Initialize all user-visible namespaces
self.init_namespaces()
# Call the actual (public) initializer
self.init_auto_alias()
# track which builtins we add, so we can clean up later
self.builtins_added = {}
# This method will add the necessary builtins for operation, but
# tracking what it did via the builtins_added dict.
#TODO: remove this, redundant
self.add_builtins()
# end __init__
def var_expand(self,cmd,depth=0):
"""Expand python variables in a string.
The depth argument indicates how many frames above the caller should
be walked to look for the local namespace where to expand variables.
The global namespace for expansion is always the user's interactive
namespace.
"""
return str(ItplNS(cmd,
self.user_ns, # globals
# Skip our own frame in searching for locals:
sys._getframe(depth+1).f_locals # locals
))
def pre_config_initialization(self):
"""Pre-configuration init method
This is called before the configuration files are processed to
prepare the services the config files might need.
self.rc already has reasonable default values at this point.
"""
rc = self.rc
try:
self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db")
except exceptions.UnicodeDecodeError:
print "Your ipythondir can't be decoded to unicode!"
print "Please set HOME environment variable to something that"
print r"only has ASCII characters, e.g. c:\home"
print "Now it is",rc.ipythondir
sys.exit()
self.shadowhist = IPython.history.ShadowHist(self.db)
def post_config_initialization(self):
"""Post configuration init method
This is called after the configuration files have been processed to
'finalize' the initialization."""
rc = self.rc
# Object inspector
self.inspector = OInspect.Inspector(OInspect.InspectColors,
PyColorize.ANSICodeColors,
'NoColor',
rc.object_info_string_level)
self.rl_next_input = None
self.rl_do_indent = False
# Load readline proper
if rc.readline:
self.init_readline()
# local shortcut, this is used a LOT
self.log = self.logger.log
# Initialize cache, set in/out prompts and printing system
self.outputcache = CachedOutput(self,
rc.cache_size,
rc.pprint,
input_sep = rc.separate_in,
output_sep = rc.separate_out,
output_sep2 = rc.separate_out2,
ps1 = rc.prompt_in1,
ps2 = rc.prompt_in2,
ps_out = rc.prompt_out,
pad_left = rc.prompts_pad_left)
# user may have over-ridden the default print hook:
try:
self.outputcache.__class__.display = self.hooks.display
except AttributeError:
pass
# I don't like assigning globally to sys, because it means when
# embedding instances, each embedded instance overrides the previous
# choice. But sys.displayhook seems to be called internally by exec,
# so I don't see a way around it. We first save the original and then
# overwrite it.
self.sys_displayhook = sys.displayhook
sys.displayhook = self.outputcache
# Do a proper resetting of doctest, including the necessary displayhook
# monkeypatching
try:
doctest_reload()
except ImportError:
warn("doctest module does not exist.")
# Set user colors (don't do it in the constructor above so that it
# doesn't crash if colors option is invalid)
self.magic_colors(rc.colors)
# Set calling of pdb on exceptions
self.call_pdb = rc.pdb
# Load user aliases
for alias in rc.alias:
self.magic_alias(alias)
self.hooks.late_startup_hook()
for cmd in self.rc.autoexec:
#print "autoexec>",cmd #dbg
self.api.runlines(cmd)
batchrun = False
for batchfile in [path(arg) for arg in self.rc.args
if arg.lower().endswith('.ipy')]:
if not batchfile.isfile():
print "No such batch file:", batchfile
continue
self.api.runlines(batchfile.text())
batchrun = True
# without -i option, exit after running the batch file
if batchrun and not self.rc.interact:
self.ask_exit()
def init_namespaces(self):
"""Initialize all user-visible namespaces to their minimum defaults.
Certain history lists are also initialized here, as they effectively
act as user namespaces.
Notes
-----
All data structures here are only filled in, they are NOT reset by this
method. If they were not empty before, data will simply be added to
therm.
"""
# The user namespace MUST have a pointer to the shell itself.
self.user_ns[self.name] = self
# Store the public api instance
self.user_ns['_ip'] = self.api
# make global variables for user access to the histories
self.user_ns['_ih'] = self.input_hist
self.user_ns['_oh'] = self.output_hist
self.user_ns['_dh'] = self.dir_hist
# user aliases to input and output histories
self.user_ns['In'] = self.input_hist
self.user_ns['Out'] = self.output_hist
self.user_ns['_sh'] = IPython.shadowns
# Fill the history zero entry, user counter starts at 1
self.input_hist.append('\n')
self.input_hist_raw.append('\n')
def add_builtins(self):
"""Store ipython references into the builtin namespace.
Some parts of ipython operate via builtins injected here, which hold a
reference to IPython itself."""
# TODO: deprecate all of these, they are unsafe
builtins_new = dict(__IPYTHON__ = self,
ip_set_hook = self.set_hook,
jobs = self.jobs,
ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'),
ipalias = wrap_deprecated(self.ipalias),
ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'),
#_ip = self.api
)
for biname,bival in builtins_new.items():
try:
# store the orignal value so we can restore it
self.builtins_added[biname] = __builtin__.__dict__[biname]
except KeyError:
# or mark that it wasn't defined, and we'll just delete it at
# cleanup
self.builtins_added[biname] = Undefined
__builtin__.__dict__[biname] = bival
# Keep in the builtins a flag for when IPython is active. We set it
# with setdefault so that multiple nested IPythons don't clobber one
# another. Each will increase its value by one upon being activated,
# which also gives us a way to determine the nesting level.
__builtin__.__dict__.setdefault('__IPYTHON__active',0)
def clean_builtins(self):
"""Remove any builtins which might have been added by add_builtins, or
restore overwritten ones to their previous values."""
for biname,bival in self.builtins_added.items():
if bival is Undefined:
del __builtin__.__dict__[biname]
else:
__builtin__.__dict__[biname] = bival