##// END OF EJS Templates
Merge branch 'master' of git://github.com/ipython/ipython into qtfrontend and fix conflicts in setupbase.py....
epatters -
r2664:6080a84e merge
parent child Browse files
Show More
@@ -0,0 +1,43 b''
1 """These kinds of tests are less than ideal, but at least they run.
2
3 This was an old test that was being run interactively in the top-level tests/
4 directory, which we are removing. For now putting this here ensures at least
5 we do run the test, though ultimately this functionality should all be tested
6 with better-isolated tests that don't rely on the global instance in iptest.
7 """
8
9 def doctest_autocall():
10 """
11 In [1]: def f1(a,b,c):
12 ...: return a+b+c
13 ...:
14
15 In [2]: def f2(a):
16 ...: return a + a
17 ...:
18
19 In [3]: ;f2 a b c
20 Out[3]: 'a b ca b c'
21
22 In [4]: assert _ == "a b ca b c"
23
24 In [5]: ,f1 a b c
25 Out[5]: 'abc'
26
27 In [6]: assert _ == 'abc'
28
29 In [7]: print _
30 abc
31
32 In [8]: /f1 1,2,3
33 Out[8]: 6
34
35 In [9]: assert _ == 6
36
37 In [10]: /f2 4
38 Out[10]: 8
39
40 In [11]: assert _ == 8
41
42 In [11]: del f1, f2
43 """
@@ -1,42 +1,42 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 A backwards compatibility layer for IPython.Shell.
4 A backwards compatibility layer for IPython.Shell.
5
5
6 Previously, IPython had an IPython.Shell module. IPython.Shell has been moved
6 Previously, IPython had an IPython.Shell module. IPython.Shell has been moved
7 to IPython.core.shell and is being refactored. This new module is provided
7 to IPython.core.shell and is being refactored. This new module is provided
8 for backwards compatability. We strongly encourage everyone to start using
8 for backwards compatability. We strongly encourage everyone to start using
9 the new code in IPython.core.shell.
9 the new code in IPython.core.shell.
10 """
10 """
11
11
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13 # Copyright (C) 2008-2009 The IPython Development Team
13 # Copyright (C) 2008-2009 The IPython Development Team
14 #
14 #
15 # Distributed under the terms of the BSD License. The full license is in
15 # Distributed under the terms of the BSD License. The full license is in
16 # the file COPYING, distributed as part of this software.
16 # the file COPYING, distributed as part of this software.
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18
18
19 from warnings import warn
19 from warnings import warn
20
20
21 msg = """
21 msg = """
22 This module (IPython.Shell) is deprecated. The classes that were in this
22 This module (IPython.Shell) is deprecated. The classes that were in this
23 module have been replaced by:
23 module have been replaced by:
24
24
25 IPShell->IPython.core.iplib.InteractiveShell
25 IPShell->IPython.core.iplib.InteractiveShell
26 IPShellEmbed->IPython.core.embed.InteractiveShellEmbed
26 IPShellEmbed->IPython.core.embed.InteractiveShellEmbed
27
27
28 Please migrate your code to use these classes instead.
28 Please migrate your code to use these classes instead.
29 """
29 """
30
30
31 warn(msg, category=DeprecationWarning, stacklevel=1)
31 warn(msg, category=DeprecationWarning, stacklevel=1)
32
32
33 from IPython.core.iplib import InteractiveShell as IPShell
33 from IPython.core.iplib import InteractiveShell as IPShell
34 from IPython.core.embed import InteractiveShellEmbed as IPShellEmbed
34 from IPython.core.embed import InteractiveShellEmbed as IPShellEmbed
35
35
36 def start(user_ns=None, embedded=False):
36 def start(user_ns=None, embedded=False):
37 """Return an instance of :class:`InteractiveShell`."""
37 """Return an instance of :class:`InteractiveShell`."""
38 if embedded:
38 if embedded:
39 return InteractiveShellEmbed(user_ns=user_ns)
39 return IPShellEmbed(user_ns=user_ns)
40 else:
40 else:
41 return InteractiveShell(user_ns=user_ns)
41 return IPShell(user_ns=user_ns)
42
42
@@ -1,180 +1,179 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """sys.excepthook for IPython itself, leaves a detailed report on disk.
2 """sys.excepthook for IPython itself, leaves a detailed report on disk.
3
3
4 Authors:
4 Authors:
5
5
6 * Fernando Perez
6 * Fernando Perez
7 * Brian E. Granger
7 * Brian E. Granger
8 """
8 """
9
9
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
11 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
12 # Copyright (C) 2008-2010 The IPython Development Team
12 # Copyright (C) 2008-2010 The IPython Development Team
13 #
13 #
14 # Distributed under the terms of the BSD License. The full license is in
14 # Distributed under the terms of the BSD License. The full license is in
15 # the file COPYING, distributed as part of this software.
15 # the file COPYING, distributed as part of this software.
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
19 # Imports
19 # Imports
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21
21
22 import os
22 import os
23 import sys
23 import sys
24 from pprint import pformat
24 from pprint import pformat
25
25
26 from IPython.core import ultratb
26 from IPython.core import ultratb
27 from IPython.external.Itpl import itpl
27 from IPython.external.Itpl import itpl
28 from IPython.utils.sysinfo import sys_info
28 from IPython.utils.sysinfo import sys_info
29
29
30 #-----------------------------------------------------------------------------
30 #-----------------------------------------------------------------------------
31 # Code
31 # Code
32 #-----------------------------------------------------------------------------
32 #-----------------------------------------------------------------------------
33
33
34 # Template for the user message.
34 # Template for the user message.
35 _default_message_template = """\
35 _default_message_template = """\
36 Oops, $self.app_name crashed. We do our best to make it stable, but...
36 Oops, $self.app_name crashed. We do our best to make it stable, but...
37
37
38 A crash report was automatically generated with the following information:
38 A crash report was automatically generated with the following information:
39 - A verbatim copy of the crash traceback.
39 - A verbatim copy of the crash traceback.
40 - A copy of your input history during this session.
40 - A copy of your input history during this session.
41 - Data on your current $self.app_name configuration.
41 - Data on your current $self.app_name configuration.
42
42
43 It was left in the file named:
43 It was left in the file named:
44 \t'$self.crash_report_fname'
44 \t'$self.crash_report_fname'
45 If you can email this file to the developers, the information in it will help
45 If you can email this file to the developers, the information in it will help
46 them in understanding and correcting the problem.
46 them in understanding and correcting the problem.
47
47
48 You can mail it to: $self.contact_name at $self.contact_email
48 You can mail it to: $self.contact_name at $self.contact_email
49 with the subject '$self.app_name Crash Report'.
49 with the subject '$self.app_name Crash Report'.
50
50
51 If you want to do it now, the following command will work (under Unix):
51 If you want to do it now, the following command will work (under Unix):
52 mail -s '$self.app_name Crash Report' $self.contact_email < $self.crash_report_fname
52 mail -s '$self.app_name Crash Report' $self.contact_email < $self.crash_report_fname
53
53
54 To ensure accurate tracking of this issue, please file a report about it at:
54 To ensure accurate tracking of this issue, please file a report about it at:
55 $self.bug_tracker
55 $self.bug_tracker
56 """
56 """
57
57
58
58
59 class CrashHandler(object):
59 class CrashHandler(object):
60 """Customizable crash handlers for IPython applications.
60 """Customizable crash handlers for IPython applications.
61
61
62 Instances of this class provide a :meth:`__call__` method which can be
62 Instances of this class provide a :meth:`__call__` method which can be
63 used as a ``sys.excepthook``. The :meth:`__call__` signature is::
63 used as a ``sys.excepthook``. The :meth:`__call__` signature is::
64
64
65 def __call__(self, etype, evalue, etb)
65 def __call__(self, etype, evalue, etb)
66 """
66 """
67
67
68 message_template = _default_message_template
68 message_template = _default_message_template
69
69
70 def __init__(self, app, contact_name=None, contact_email=None,
70 def __init__(self, app, contact_name=None, contact_email=None,
71 bug_tracker=None, show_crash_traceback=True, call_pdb=False):
71 bug_tracker=None, show_crash_traceback=True, call_pdb=False):
72 """Create a new crash handler
72 """Create a new crash handler
73
73
74 Parameters
74 Parameters
75 ----------
75 ----------
76 app : Application
76 app : Application
77 A running :class:`Application` instance, which will be queried at
77 A running :class:`Application` instance, which will be queried at
78 crash time for internal information.
78 crash time for internal information.
79
79
80 contact_name : str
80 contact_name : str
81 A string with the name of the person to contact.
81 A string with the name of the person to contact.
82
82
83 contact_email : str
83 contact_email : str
84 A string with the email address of the contact.
84 A string with the email address of the contact.
85
85
86 bug_tracker : str
86 bug_tracker : str
87 A string with the URL for your project's bug tracker.
87 A string with the URL for your project's bug tracker.
88
88
89 show_crash_traceback : bool
89 show_crash_traceback : bool
90 If false, don't print the crash traceback on stderr, only generate
90 If false, don't print the crash traceback on stderr, only generate
91 the on-disk report
91 the on-disk report
92
92
93 Non-argument instance attributes:
93 Non-argument instance attributes:
94
94
95 These instances contain some non-argument attributes which allow for
95 These instances contain some non-argument attributes which allow for
96 further customization of the crash handler's behavior. Please see the
96 further customization of the crash handler's behavior. Please see the
97 source for further details.
97 source for further details.
98 """
98 """
99 self.app = app
99 self.app = app
100 self.app_name = self.app.name
100 self.app_name = self.app.name
101 self.contact_name = contact_name
101 self.contact_name = contact_name
102 self.contact_email = contact_email
102 self.contact_email = contact_email
103 self.bug_tracker = bug_tracker
103 self.bug_tracker = bug_tracker
104 self.crash_report_fname = "Crash_report_%s.txt" % self.app_name
104 self.crash_report_fname = "Crash_report_%s.txt" % self.app_name
105 self.show_crash_traceback = show_crash_traceback
105 self.show_crash_traceback = show_crash_traceback
106 self.section_sep = '\n\n'+'*'*75+'\n\n'
106 self.section_sep = '\n\n'+'*'*75+'\n\n'
107 self.call_pdb = call_pdb
107 self.call_pdb = call_pdb
108 #self.call_pdb = True # dbg
108 #self.call_pdb = True # dbg
109
109
110 def __call__(self, etype, evalue, etb):
110 def __call__(self, etype, evalue, etb):
111 """Handle an exception, call for compatible with sys.excepthook"""
111 """Handle an exception, call for compatible with sys.excepthook"""
112
112
113 # Report tracebacks shouldn't use color in general (safer for users)
113 # Report tracebacks shouldn't use color in general (safer for users)
114 color_scheme = 'NoColor'
114 color_scheme = 'NoColor'
115
115
116 # Use this ONLY for developer debugging (keep commented out for release)
116 # Use this ONLY for developer debugging (keep commented out for release)
117 #color_scheme = 'Linux' # dbg
117 #color_scheme = 'Linux' # dbg
118
119 try:
118 try:
120 rptdir = self.app.ipython_dir
119 rptdir = self.app.ipython_dir
121 except:
120 except:
122 rptdir = os.getcwd()
121 rptdir = os.getcwd()
123 if not os.path.isdir(rptdir):
122 if rptdir is None or not os.path.isdir(rptdir):
124 rptdir = os.getcwd()
123 rptdir = os.getcwd()
125 report_name = os.path.join(rptdir,self.crash_report_fname)
124 report_name = os.path.join(rptdir,self.crash_report_fname)
126 # write the report filename into the instance dict so it can get
125 # write the report filename into the instance dict so it can get
127 # properly expanded out in the user message template
126 # properly expanded out in the user message template
128 self.crash_report_fname = report_name
127 self.crash_report_fname = report_name
129 TBhandler = ultratb.VerboseTB(
128 TBhandler = ultratb.VerboseTB(
130 color_scheme=color_scheme,
129 color_scheme=color_scheme,
131 long_header=1,
130 long_header=1,
132 call_pdb=self.call_pdb,
131 call_pdb=self.call_pdb,
133 )
132 )
134 if self.call_pdb:
133 if self.call_pdb:
135 TBhandler(etype,evalue,etb)
134 TBhandler(etype,evalue,etb)
136 return
135 return
137 else:
136 else:
138 traceback = TBhandler.text(etype,evalue,etb,context=31)
137 traceback = TBhandler.text(etype,evalue,etb,context=31)
139
138
140 # print traceback to screen
139 # print traceback to screen
141 if self.show_crash_traceback:
140 if self.show_crash_traceback:
142 print >> sys.stderr, traceback
141 print >> sys.stderr, traceback
143
142
144 # and generate a complete report on disk
143 # and generate a complete report on disk
145 try:
144 try:
146 report = open(report_name,'w')
145 report = open(report_name,'w')
147 except:
146 except:
148 print >> sys.stderr, 'Could not create crash report on disk.'
147 print >> sys.stderr, 'Could not create crash report on disk.'
149 return
148 return
150
149
151 # Inform user on stderr of what happened
150 # Inform user on stderr of what happened
152 msg = itpl('\n'+'*'*70+'\n'+self.message_template)
151 msg = itpl('\n'+'*'*70+'\n'+self.message_template)
153 print >> sys.stderr, msg
152 print >> sys.stderr, msg
154
153
155 # Construct report on disk
154 # Construct report on disk
156 report.write(self.make_report(traceback))
155 report.write(self.make_report(traceback))
157 report.close()
156 report.close()
158 raw_input("Hit <Enter> to quit this message (your terminal may close):")
157 raw_input("Hit <Enter> to quit this message (your terminal may close):")
159
158
160 def make_report(self,traceback):
159 def make_report(self,traceback):
161 """Return a string containing a crash report."""
160 """Return a string containing a crash report."""
162
161
163 sec_sep = self.section_sep
162 sec_sep = self.section_sep
164
163
165 report = ['*'*75+'\n\n'+'IPython post-mortem report\n\n']
164 report = ['*'*75+'\n\n'+'IPython post-mortem report\n\n']
166 rpt_add = report.append
165 rpt_add = report.append
167 rpt_add(sys_info())
166 rpt_add(sys_info())
168
167
169 try:
168 try:
170 config = pformat(self.app.config)
169 config = pformat(self.app.config)
171 rpt_add(sec_sep)
170 rpt_add(sec_sep)
172 rpt_add('Application name: %s\n\n' % self.app_name)
171 rpt_add('Application name: %s\n\n' % self.app_name)
173 rpt_add('Current user configuration structure:\n\n')
172 rpt_add('Current user configuration structure:\n\n')
174 rpt_add(config)
173 rpt_add(config)
175 except:
174 except:
176 pass
175 pass
177 rpt_add(sec_sep+'Crash traceback:\n\n' + traceback)
176 rpt_add(sec_sep+'Crash traceback:\n\n' + traceback)
178
177
179 return ''.join(report)
178 return ''.join(report)
180
179
@@ -1,3700 +1,3708 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """Magic functions for InteractiveShell.
2 """Magic functions for InteractiveShell.
3 """
3 """
4
4
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
7 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
8 # Copyright (C) 2008-2009 The IPython Development Team
8 # Copyright (C) 2008-2009 The IPython Development Team
9
9
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13
13
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15 # Imports
15 # Imports
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 import __builtin__
18 import __builtin__
19 import __future__
19 import __future__
20 import bdb
20 import bdb
21 import inspect
21 import inspect
22 import os
22 import os
23 import sys
23 import sys
24 import shutil
24 import shutil
25 import re
25 import re
26 import time
26 import time
27 import textwrap
27 import textwrap
28 import types
28 import types
29 from cStringIO import StringIO
29 from cStringIO import StringIO
30 from getopt import getopt,GetoptError
30 from getopt import getopt,GetoptError
31 from pprint import pformat
31 from pprint import pformat
32
32
33 # cProfile was added in Python2.5
33 # cProfile was added in Python2.5
34 try:
34 try:
35 import cProfile as profile
35 import cProfile as profile
36 import pstats
36 import pstats
37 except ImportError:
37 except ImportError:
38 # profile isn't bundled by default in Debian for license reasons
38 # profile isn't bundled by default in Debian for license reasons
39 try:
39 try:
40 import profile,pstats
40 import profile,pstats
41 except ImportError:
41 except ImportError:
42 profile = pstats = None
42 profile = pstats = None
43
43
44 # print_function was added to __future__ in Python2.6, remove this when we drop
44 # print_function was added to __future__ in Python2.6, remove this when we drop
45 # 2.5 compatibility
45 # 2.5 compatibility
46 if not hasattr(__future__,'CO_FUTURE_PRINT_FUNCTION'):
46 if not hasattr(__future__,'CO_FUTURE_PRINT_FUNCTION'):
47 __future__.CO_FUTURE_PRINT_FUNCTION = 65536
47 __future__.CO_FUTURE_PRINT_FUNCTION = 65536
48
48
49 import IPython
49 import IPython
50 from IPython.core import debugger, oinspect
50 from IPython.core import debugger, oinspect
51 from IPython.core.error import TryNext
51 from IPython.core.error import TryNext
52 from IPython.core.error import UsageError
52 from IPython.core.error import UsageError
53 from IPython.core.fakemodule import FakeModule
53 from IPython.core.fakemodule import FakeModule
54 from IPython.core.macro import Macro
54 from IPython.core.macro import Macro
55 from IPython.core.page import page
55 from IPython.core.page import page
56 from IPython.core.prefilter import ESC_MAGIC
56 from IPython.core.prefilter import ESC_MAGIC
57 from IPython.lib.pylabtools import mpl_runner
57 from IPython.lib.pylabtools import mpl_runner
58 from IPython.lib.inputhook import enable_gui
58 from IPython.lib.inputhook import enable_gui
59 from IPython.external.Itpl import itpl, printpl
59 from IPython.external.Itpl import itpl, printpl
60 from IPython.testing import decorators as testdec
60 from IPython.testing import decorators as testdec
61 from IPython.utils.io import Term, file_read, nlprint
61 from IPython.utils.io import Term, file_read, nlprint
62 from IPython.utils.path import get_py_filename
62 from IPython.utils.path import get_py_filename
63 from IPython.utils.process import arg_split, abbrev_cwd
63 from IPython.utils.process import arg_split, abbrev_cwd
64 from IPython.utils.terminal import set_term_title
64 from IPython.utils.terminal import set_term_title
65 from IPython.utils.text import LSString, SList, StringTypes
65 from IPython.utils.text import LSString, SList, StringTypes
66 from IPython.utils.timing import clock, clock2
66 from IPython.utils.timing import clock, clock2
67 from IPython.utils.warn import warn, error
67 from IPython.utils.warn import warn, error
68 from IPython.utils.ipstruct import Struct
68 from IPython.utils.ipstruct import Struct
69 import IPython.utils.generics
69 import IPython.utils.generics
70
70
71 #-----------------------------------------------------------------------------
71 #-----------------------------------------------------------------------------
72 # Utility functions
72 # Utility functions
73 #-----------------------------------------------------------------------------
73 #-----------------------------------------------------------------------------
74
74
75 def on_off(tag):
75 def on_off(tag):
76 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
76 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
77 return ['OFF','ON'][tag]
77 return ['OFF','ON'][tag]
78
78
79 class Bunch: pass
79 class Bunch: pass
80
80
81 def compress_dhist(dh):
81 def compress_dhist(dh):
82 head, tail = dh[:-10], dh[-10:]
82 head, tail = dh[:-10], dh[-10:]
83
83
84 newhead = []
84 newhead = []
85 done = set()
85 done = set()
86 for h in head:
86 for h in head:
87 if h in done:
87 if h in done:
88 continue
88 continue
89 newhead.append(h)
89 newhead.append(h)
90 done.add(h)
90 done.add(h)
91
91
92 return newhead + tail
92 return newhead + tail
93
93
94
94
95 #***************************************************************************
95 #***************************************************************************
96 # Main class implementing Magic functionality
96 # Main class implementing Magic functionality
97
97
98 # XXX - for some odd reason, if Magic is made a new-style class, we get errors
98 # XXX - for some odd reason, if Magic is made a new-style class, we get errors
99 # on construction of the main InteractiveShell object. Something odd is going
99 # on construction of the main InteractiveShell object. Something odd is going
100 # on with super() calls, Component and the MRO... For now leave it as-is, but
100 # on with super() calls, Component and the MRO... For now leave it as-is, but
101 # eventually this needs to be clarified.
101 # eventually this needs to be clarified.
102 # BG: This is because InteractiveShell inherits from this, but is itself a
102 # BG: This is because InteractiveShell inherits from this, but is itself a
103 # Component. This messes up the MRO in some way. The fix is that we need to
103 # Component. This messes up the MRO in some way. The fix is that we need to
104 # make Magic a component that InteractiveShell does not subclass.
104 # make Magic a component that InteractiveShell does not subclass.
105
105
106 class Magic:
106 class Magic:
107 """Magic functions for InteractiveShell.
107 """Magic functions for InteractiveShell.
108
108
109 Shell functions which can be reached as %function_name. All magic
109 Shell functions which can be reached as %function_name. All magic
110 functions should accept a string, which they can parse for their own
110 functions should accept a string, which they can parse for their own
111 needs. This can make some functions easier to type, eg `%cd ../`
111 needs. This can make some functions easier to type, eg `%cd ../`
112 vs. `%cd("../")`
112 vs. `%cd("../")`
113
113
114 ALL definitions MUST begin with the prefix magic_. The user won't need it
114 ALL definitions MUST begin with the prefix magic_. The user won't need it
115 at the command line, but it is is needed in the definition. """
115 at the command line, but it is is needed in the definition. """
116
116
117 # class globals
117 # class globals
118 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
118 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
119 'Automagic is ON, % prefix NOT needed for magic functions.']
119 'Automagic is ON, % prefix NOT needed for magic functions.']
120
120
121 #......................................................................
121 #......................................................................
122 # some utility functions
122 # some utility functions
123
123
124 def __init__(self,shell):
124 def __init__(self,shell):
125
125
126 self.options_table = {}
126 self.options_table = {}
127 if profile is None:
127 if profile is None:
128 self.magic_prun = self.profile_missing_notice
128 self.magic_prun = self.profile_missing_notice
129 self.shell = shell
129 self.shell = shell
130
130
131 # namespace for holding state we may need
131 # namespace for holding state we may need
132 self._magic_state = Bunch()
132 self._magic_state = Bunch()
133
133
134 def profile_missing_notice(self, *args, **kwargs):
134 def profile_missing_notice(self, *args, **kwargs):
135 error("""\
135 error("""\
136 The profile module could not be found. It has been removed from the standard
136 The profile module could not be found. It has been removed from the standard
137 python packages because of its non-free license. To use profiling, install the
137 python packages because of its non-free license. To use profiling, install the
138 python-profiler package from non-free.""")
138 python-profiler package from non-free.""")
139
139
140 def default_option(self,fn,optstr):
140 def default_option(self,fn,optstr):
141 """Make an entry in the options_table for fn, with value optstr"""
141 """Make an entry in the options_table for fn, with value optstr"""
142
142
143 if fn not in self.lsmagic():
143 if fn not in self.lsmagic():
144 error("%s is not a magic function" % fn)
144 error("%s is not a magic function" % fn)
145 self.options_table[fn] = optstr
145 self.options_table[fn] = optstr
146
146
147 def lsmagic(self):
147 def lsmagic(self):
148 """Return a list of currently available magic functions.
148 """Return a list of currently available magic functions.
149
149
150 Gives a list of the bare names after mangling (['ls','cd', ...], not
150 Gives a list of the bare names after mangling (['ls','cd', ...], not
151 ['magic_ls','magic_cd',...]"""
151 ['magic_ls','magic_cd',...]"""
152
152
153 # FIXME. This needs a cleanup, in the way the magics list is built.
153 # FIXME. This needs a cleanup, in the way the magics list is built.
154
154
155 # magics in class definition
155 # magics in class definition
156 class_magic = lambda fn: fn.startswith('magic_') and \
156 class_magic = lambda fn: fn.startswith('magic_') and \
157 callable(Magic.__dict__[fn])
157 callable(Magic.__dict__[fn])
158 # in instance namespace (run-time user additions)
158 # in instance namespace (run-time user additions)
159 inst_magic = lambda fn: fn.startswith('magic_') and \
159 inst_magic = lambda fn: fn.startswith('magic_') and \
160 callable(self.__dict__[fn])
160 callable(self.__dict__[fn])
161 # and bound magics by user (so they can access self):
161 # and bound magics by user (so they can access self):
162 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
162 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
163 callable(self.__class__.__dict__[fn])
163 callable(self.__class__.__dict__[fn])
164 magics = filter(class_magic,Magic.__dict__.keys()) + \
164 magics = filter(class_magic,Magic.__dict__.keys()) + \
165 filter(inst_magic,self.__dict__.keys()) + \
165 filter(inst_magic,self.__dict__.keys()) + \
166 filter(inst_bound_magic,self.__class__.__dict__.keys())
166 filter(inst_bound_magic,self.__class__.__dict__.keys())
167 out = []
167 out = []
168 for fn in set(magics):
168 for fn in set(magics):
169 out.append(fn.replace('magic_','',1))
169 out.append(fn.replace('magic_','',1))
170 out.sort()
170 out.sort()
171 return out
171 return out
172
172
173 def extract_input_slices(self,slices,raw=False):
173 def extract_input_slices(self,slices,raw=False):
174 """Return as a string a set of input history slices.
174 """Return as a string a set of input history slices.
175
175
176 Inputs:
176 Inputs:
177
177
178 - slices: the set of slices is given as a list of strings (like
178 - slices: the set of slices is given as a list of strings (like
179 ['1','4:8','9'], since this function is for use by magic functions
179 ['1','4:8','9'], since this function is for use by magic functions
180 which get their arguments as strings.
180 which get their arguments as strings.
181
181
182 Optional inputs:
182 Optional inputs:
183
183
184 - raw(False): by default, the processed input is used. If this is
184 - raw(False): by default, the processed input is used. If this is
185 true, the raw input history is used instead.
185 true, the raw input history is used instead.
186
186
187 Note that slices can be called with two notations:
187 Note that slices can be called with two notations:
188
188
189 N:M -> standard python form, means including items N...(M-1).
189 N:M -> standard python form, means including items N...(M-1).
190
190
191 N-M -> include items N..M (closed endpoint)."""
191 N-M -> include items N..M (closed endpoint)."""
192
192
193 if raw:
193 if raw:
194 hist = self.shell.input_hist_raw
194 hist = self.shell.input_hist_raw
195 else:
195 else:
196 hist = self.shell.input_hist
196 hist = self.shell.input_hist
197
197
198 cmds = []
198 cmds = []
199 for chunk in slices:
199 for chunk in slices:
200 if ':' in chunk:
200 if ':' in chunk:
201 ini,fin = map(int,chunk.split(':'))
201 ini,fin = map(int,chunk.split(':'))
202 elif '-' in chunk:
202 elif '-' in chunk:
203 ini,fin = map(int,chunk.split('-'))
203 ini,fin = map(int,chunk.split('-'))
204 fin += 1
204 fin += 1
205 else:
205 else:
206 ini = int(chunk)
206 ini = int(chunk)
207 fin = ini+1
207 fin = ini+1
208 cmds.append(hist[ini:fin])
208 cmds.append(hist[ini:fin])
209 return cmds
209 return cmds
210
210
211 def _ofind(self, oname, namespaces=None):
211 def _ofind(self, oname, namespaces=None):
212 """Find an object in the available namespaces.
212 """Find an object in the available namespaces.
213
213
214 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
214 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
215
215
216 Has special code to detect magic functions.
216 Has special code to detect magic functions.
217 """
217 """
218 oname = oname.strip()
218 oname = oname.strip()
219 alias_ns = None
219 alias_ns = None
220 if namespaces is None:
220 if namespaces is None:
221 # Namespaces to search in:
221 # Namespaces to search in:
222 # Put them in a list. The order is important so that we
222 # Put them in a list. The order is important so that we
223 # find things in the same order that Python finds them.
223 # find things in the same order that Python finds them.
224 namespaces = [ ('Interactive', self.shell.user_ns),
224 namespaces = [ ('Interactive', self.shell.user_ns),
225 ('IPython internal', self.shell.internal_ns),
225 ('IPython internal', self.shell.internal_ns),
226 ('Python builtin', __builtin__.__dict__),
226 ('Python builtin', __builtin__.__dict__),
227 ('Alias', self.shell.alias_manager.alias_table),
227 ('Alias', self.shell.alias_manager.alias_table),
228 ]
228 ]
229 alias_ns = self.shell.alias_manager.alias_table
229 alias_ns = self.shell.alias_manager.alias_table
230
230
231 # initialize results to 'null'
231 # initialize results to 'null'
232 found = False; obj = None; ospace = None; ds = None;
232 found = False; obj = None; ospace = None; ds = None;
233 ismagic = False; isalias = False; parent = None
233 ismagic = False; isalias = False; parent = None
234
234
235 # We need to special-case 'print', which as of python2.6 registers as a
235 # We need to special-case 'print', which as of python2.6 registers as a
236 # function but should only be treated as one if print_function was
236 # function but should only be treated as one if print_function was
237 # loaded with a future import. In this case, just bail.
237 # loaded with a future import. In this case, just bail.
238 if (oname == 'print' and not (self.shell.compile.compiler.flags &
238 if (oname == 'print' and not (self.shell.compile.compiler.flags &
239 __future__.CO_FUTURE_PRINT_FUNCTION)):
239 __future__.CO_FUTURE_PRINT_FUNCTION)):
240 return {'found':found, 'obj':obj, 'namespace':ospace,
240 return {'found':found, 'obj':obj, 'namespace':ospace,
241 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
241 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
242
242
243 # Look for the given name by splitting it in parts. If the head is
243 # Look for the given name by splitting it in parts. If the head is
244 # found, then we look for all the remaining parts as members, and only
244 # found, then we look for all the remaining parts as members, and only
245 # declare success if we can find them all.
245 # declare success if we can find them all.
246 oname_parts = oname.split('.')
246 oname_parts = oname.split('.')
247 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
247 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
248 for nsname,ns in namespaces:
248 for nsname,ns in namespaces:
249 try:
249 try:
250 obj = ns[oname_head]
250 obj = ns[oname_head]
251 except KeyError:
251 except KeyError:
252 continue
252 continue
253 else:
253 else:
254 #print 'oname_rest:', oname_rest # dbg
254 #print 'oname_rest:', oname_rest # dbg
255 for part in oname_rest:
255 for part in oname_rest:
256 try:
256 try:
257 parent = obj
257 parent = obj
258 obj = getattr(obj,part)
258 obj = getattr(obj,part)
259 except:
259 except:
260 # Blanket except b/c some badly implemented objects
260 # Blanket except b/c some badly implemented objects
261 # allow __getattr__ to raise exceptions other than
261 # allow __getattr__ to raise exceptions other than
262 # AttributeError, which then crashes IPython.
262 # AttributeError, which then crashes IPython.
263 break
263 break
264 else:
264 else:
265 # If we finish the for loop (no break), we got all members
265 # If we finish the for loop (no break), we got all members
266 found = True
266 found = True
267 ospace = nsname
267 ospace = nsname
268 if ns == alias_ns:
268 if ns == alias_ns:
269 isalias = True
269 isalias = True
270 break # namespace loop
270 break # namespace loop
271
271
272 # Try to see if it's magic
272 # Try to see if it's magic
273 if not found:
273 if not found:
274 if oname.startswith(ESC_MAGIC):
274 if oname.startswith(ESC_MAGIC):
275 oname = oname[1:]
275 oname = oname[1:]
276 obj = getattr(self,'magic_'+oname,None)
276 obj = getattr(self,'magic_'+oname,None)
277 if obj is not None:
277 if obj is not None:
278 found = True
278 found = True
279 ospace = 'IPython internal'
279 ospace = 'IPython internal'
280 ismagic = True
280 ismagic = True
281
281
282 # Last try: special-case some literals like '', [], {}, etc:
282 # Last try: special-case some literals like '', [], {}, etc:
283 if not found and oname_head in ["''",'""','[]','{}','()']:
283 if not found and oname_head in ["''",'""','[]','{}','()']:
284 obj = eval(oname_head)
284 obj = eval(oname_head)
285 found = True
285 found = True
286 ospace = 'Interactive'
286 ospace = 'Interactive'
287
287
288 return {'found':found, 'obj':obj, 'namespace':ospace,
288 return {'found':found, 'obj':obj, 'namespace':ospace,
289 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
289 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
290
290
291 def arg_err(self,func):
291 def arg_err(self,func):
292 """Print docstring if incorrect arguments were passed"""
292 """Print docstring if incorrect arguments were passed"""
293 print 'Error in arguments:'
293 print 'Error in arguments:'
294 print oinspect.getdoc(func)
294 print oinspect.getdoc(func)
295
295
296 def format_latex(self,strng):
296 def format_latex(self,strng):
297 """Format a string for latex inclusion."""
297 """Format a string for latex inclusion."""
298
298
299 # Characters that need to be escaped for latex:
299 # Characters that need to be escaped for latex:
300 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
300 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
301 # Magic command names as headers:
301 # Magic command names as headers:
302 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
302 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
303 re.MULTILINE)
303 re.MULTILINE)
304 # Magic commands
304 # Magic commands
305 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
305 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
306 re.MULTILINE)
306 re.MULTILINE)
307 # Paragraph continue
307 # Paragraph continue
308 par_re = re.compile(r'\\$',re.MULTILINE)
308 par_re = re.compile(r'\\$',re.MULTILINE)
309
309
310 # The "\n" symbol
310 # The "\n" symbol
311 newline_re = re.compile(r'\\n')
311 newline_re = re.compile(r'\\n')
312
312
313 # Now build the string for output:
313 # Now build the string for output:
314 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
314 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
315 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
315 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
316 strng)
316 strng)
317 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
317 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
318 strng = par_re.sub(r'\\\\',strng)
318 strng = par_re.sub(r'\\\\',strng)
319 strng = escape_re.sub(r'\\\1',strng)
319 strng = escape_re.sub(r'\\\1',strng)
320 strng = newline_re.sub(r'\\textbackslash{}n',strng)
320 strng = newline_re.sub(r'\\textbackslash{}n',strng)
321 return strng
321 return strng
322
322
323 def format_screen(self,strng):
323 def format_screen(self,strng):
324 """Format a string for screen printing.
324 """Format a string for screen printing.
325
325
326 This removes some latex-type format codes."""
326 This removes some latex-type format codes."""
327 # Paragraph continue
327 # Paragraph continue
328 par_re = re.compile(r'\\$',re.MULTILINE)
328 par_re = re.compile(r'\\$',re.MULTILINE)
329 strng = par_re.sub('',strng)
329 strng = par_re.sub('',strng)
330 return strng
330 return strng
331
331
332 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
332 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
333 """Parse options passed to an argument string.
333 """Parse options passed to an argument string.
334
334
335 The interface is similar to that of getopt(), but it returns back a
335 The interface is similar to that of getopt(), but it returns back a
336 Struct with the options as keys and the stripped argument string still
336 Struct with the options as keys and the stripped argument string still
337 as a string.
337 as a string.
338
338
339 arg_str is quoted as a true sys.argv vector by using shlex.split.
339 arg_str is quoted as a true sys.argv vector by using shlex.split.
340 This allows us to easily expand variables, glob files, quote
340 This allows us to easily expand variables, glob files, quote
341 arguments, etc.
341 arguments, etc.
342
342
343 Options:
343 Options:
344 -mode: default 'string'. If given as 'list', the argument string is
344 -mode: default 'string'. If given as 'list', the argument string is
345 returned as a list (split on whitespace) instead of a string.
345 returned as a list (split on whitespace) instead of a string.
346
346
347 -list_all: put all option values in lists. Normally only options
347 -list_all: put all option values in lists. Normally only options
348 appearing more than once are put in a list.
348 appearing more than once are put in a list.
349
349
350 -posix (True): whether to split the input line in POSIX mode or not,
350 -posix (True): whether to split the input line in POSIX mode or not,
351 as per the conventions outlined in the shlex module from the
351 as per the conventions outlined in the shlex module from the
352 standard library."""
352 standard library."""
353
353
354 # inject default options at the beginning of the input line
354 # inject default options at the beginning of the input line
355 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
355 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
356 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
356 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
357
357
358 mode = kw.get('mode','string')
358 mode = kw.get('mode','string')
359 if mode not in ['string','list']:
359 if mode not in ['string','list']:
360 raise ValueError,'incorrect mode given: %s' % mode
360 raise ValueError,'incorrect mode given: %s' % mode
361 # Get options
361 # Get options
362 list_all = kw.get('list_all',0)
362 list_all = kw.get('list_all',0)
363 posix = kw.get('posix', os.name == 'posix')
363 posix = kw.get('posix', os.name == 'posix')
364
364
365 # Check if we have more than one argument to warrant extra processing:
365 # Check if we have more than one argument to warrant extra processing:
366 odict = {} # Dictionary with options
366 odict = {} # Dictionary with options
367 args = arg_str.split()
367 args = arg_str.split()
368 if len(args) >= 1:
368 if len(args) >= 1:
369 # If the list of inputs only has 0 or 1 thing in it, there's no
369 # If the list of inputs only has 0 or 1 thing in it, there's no
370 # need to look for options
370 # need to look for options
371 argv = arg_split(arg_str,posix)
371 argv = arg_split(arg_str,posix)
372 # Do regular option processing
372 # Do regular option processing
373 try:
373 try:
374 opts,args = getopt(argv,opt_str,*long_opts)
374 opts,args = getopt(argv,opt_str,*long_opts)
375 except GetoptError,e:
375 except GetoptError,e:
376 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
376 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
377 " ".join(long_opts)))
377 " ".join(long_opts)))
378 for o,a in opts:
378 for o,a in opts:
379 if o.startswith('--'):
379 if o.startswith('--'):
380 o = o[2:]
380 o = o[2:]
381 else:
381 else:
382 o = o[1:]
382 o = o[1:]
383 try:
383 try:
384 odict[o].append(a)
384 odict[o].append(a)
385 except AttributeError:
385 except AttributeError:
386 odict[o] = [odict[o],a]
386 odict[o] = [odict[o],a]
387 except KeyError:
387 except KeyError:
388 if list_all:
388 if list_all:
389 odict[o] = [a]
389 odict[o] = [a]
390 else:
390 else:
391 odict[o] = a
391 odict[o] = a
392
392
393 # Prepare opts,args for return
393 # Prepare opts,args for return
394 opts = Struct(odict)
394 opts = Struct(odict)
395 if mode == 'string':
395 if mode == 'string':
396 args = ' '.join(args)
396 args = ' '.join(args)
397
397
398 return opts,args
398 return opts,args
399
399
400 #......................................................................
400 #......................................................................
401 # And now the actual magic functions
401 # And now the actual magic functions
402
402
403 # Functions for IPython shell work (vars,funcs, config, etc)
403 # Functions for IPython shell work (vars,funcs, config, etc)
404 def magic_lsmagic(self, parameter_s = ''):
404 def magic_lsmagic(self, parameter_s = ''):
405 """List currently available magic functions."""
405 """List currently available magic functions."""
406 mesc = ESC_MAGIC
406 mesc = ESC_MAGIC
407 print 'Available magic functions:\n'+mesc+\
407 print 'Available magic functions:\n'+mesc+\
408 (' '+mesc).join(self.lsmagic())
408 (' '+mesc).join(self.lsmagic())
409 print '\n' + Magic.auto_status[self.shell.automagic]
409 print '\n' + Magic.auto_status[self.shell.automagic]
410 return None
410 return None
411
411
412 def magic_magic(self, parameter_s = ''):
412 def magic_magic(self, parameter_s = ''):
413 """Print information about the magic function system.
413 """Print information about the magic function system.
414
414
415 Supported formats: -latex, -brief, -rest
415 Supported formats: -latex, -brief, -rest
416 """
416 """
417
417
418 mode = ''
418 mode = ''
419 try:
419 try:
420 if parameter_s.split()[0] == '-latex':
420 if parameter_s.split()[0] == '-latex':
421 mode = 'latex'
421 mode = 'latex'
422 if parameter_s.split()[0] == '-brief':
422 if parameter_s.split()[0] == '-brief':
423 mode = 'brief'
423 mode = 'brief'
424 if parameter_s.split()[0] == '-rest':
424 if parameter_s.split()[0] == '-rest':
425 mode = 'rest'
425 mode = 'rest'
426 rest_docs = []
426 rest_docs = []
427 except:
427 except:
428 pass
428 pass
429
429
430 magic_docs = []
430 magic_docs = []
431 for fname in self.lsmagic():
431 for fname in self.lsmagic():
432 mname = 'magic_' + fname
432 mname = 'magic_' + fname
433 for space in (Magic,self,self.__class__):
433 for space in (Magic,self,self.__class__):
434 try:
434 try:
435 fn = space.__dict__[mname]
435 fn = space.__dict__[mname]
436 except KeyError:
436 except KeyError:
437 pass
437 pass
438 else:
438 else:
439 break
439 break
440 if mode == 'brief':
440 if mode == 'brief':
441 # only first line
441 # only first line
442 if fn.__doc__:
442 if fn.__doc__:
443 fndoc = fn.__doc__.split('\n',1)[0]
443 fndoc = fn.__doc__.split('\n',1)[0]
444 else:
444 else:
445 fndoc = 'No documentation'
445 fndoc = 'No documentation'
446 else:
446 else:
447 if fn.__doc__:
447 if fn.__doc__:
448 fndoc = fn.__doc__.rstrip()
448 fndoc = fn.__doc__.rstrip()
449 else:
449 else:
450 fndoc = 'No documentation'
450 fndoc = 'No documentation'
451
451
452
452
453 if mode == 'rest':
453 if mode == 'rest':
454 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
454 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
455 fname,fndoc))
455 fname,fndoc))
456
456
457 else:
457 else:
458 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
458 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
459 fname,fndoc))
459 fname,fndoc))
460
460
461 magic_docs = ''.join(magic_docs)
461 magic_docs = ''.join(magic_docs)
462
462
463 if mode == 'rest':
463 if mode == 'rest':
464 return "".join(rest_docs)
464 return "".join(rest_docs)
465
465
466 if mode == 'latex':
466 if mode == 'latex':
467 print self.format_latex(magic_docs)
467 print self.format_latex(magic_docs)
468 return
468 return
469 else:
469 else:
470 magic_docs = self.format_screen(magic_docs)
470 magic_docs = self.format_screen(magic_docs)
471 if mode == 'brief':
471 if mode == 'brief':
472 return magic_docs
472 return magic_docs
473
473
474 outmsg = """
474 outmsg = """
475 IPython's 'magic' functions
475 IPython's 'magic' functions
476 ===========================
476 ===========================
477
477
478 The magic function system provides a series of functions which allow you to
478 The magic function system provides a series of functions which allow you to
479 control the behavior of IPython itself, plus a lot of system-type
479 control the behavior of IPython itself, plus a lot of system-type
480 features. All these functions are prefixed with a % character, but parameters
480 features. All these functions are prefixed with a % character, but parameters
481 are given without parentheses or quotes.
481 are given without parentheses or quotes.
482
482
483 NOTE: If you have 'automagic' enabled (via the command line option or with the
483 NOTE: If you have 'automagic' enabled (via the command line option or with the
484 %automagic function), you don't need to type in the % explicitly. By default,
484 %automagic function), you don't need to type in the % explicitly. By default,
485 IPython ships with automagic on, so you should only rarely need the % escape.
485 IPython ships with automagic on, so you should only rarely need the % escape.
486
486
487 Example: typing '%cd mydir' (without the quotes) changes you working directory
487 Example: typing '%cd mydir' (without the quotes) changes you working directory
488 to 'mydir', if it exists.
488 to 'mydir', if it exists.
489
489
490 You can define your own magic functions to extend the system. See the supplied
490 You can define your own magic functions to extend the system. See the supplied
491 ipythonrc and example-magic.py files for details (in your ipython
491 ipythonrc and example-magic.py files for details (in your ipython
492 configuration directory, typically $HOME/.ipython/).
492 configuration directory, typically $HOME/.ipython/).
493
493
494 You can also define your own aliased names for magic functions. In your
494 You can also define your own aliased names for magic functions. In your
495 ipythonrc file, placing a line like:
495 ipythonrc file, placing a line like:
496
496
497 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
497 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
498
498
499 will define %pf as a new name for %profile.
499 will define %pf as a new name for %profile.
500
500
501 You can also call magics in code using the magic() function, which IPython
501 You can also call magics in code using the magic() function, which IPython
502 automatically adds to the builtin namespace. Type 'magic?' for details.
502 automatically adds to the builtin namespace. Type 'magic?' for details.
503
503
504 For a list of the available magic functions, use %lsmagic. For a description
504 For a list of the available magic functions, use %lsmagic. For a description
505 of any of them, type %magic_name?, e.g. '%cd?'.
505 of any of them, type %magic_name?, e.g. '%cd?'.
506
506
507 Currently the magic system has the following functions:\n"""
507 Currently the magic system has the following functions:\n"""
508
508
509 mesc = ESC_MAGIC
509 mesc = ESC_MAGIC
510 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
510 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
511 "\n\n%s%s\n\n%s" % (outmsg,
511 "\n\n%s%s\n\n%s" % (outmsg,
512 magic_docs,mesc,mesc,
512 magic_docs,mesc,mesc,
513 (' '+mesc).join(self.lsmagic()),
513 (' '+mesc).join(self.lsmagic()),
514 Magic.auto_status[self.shell.automagic] ) )
514 Magic.auto_status[self.shell.automagic] ) )
515
515
516 page(outmsg,screen_lines=self.shell.usable_screen_length)
516 page(outmsg,screen_lines=self.shell.usable_screen_length)
517
517
518
518
519 def magic_autoindent(self, parameter_s = ''):
519 def magic_autoindent(self, parameter_s = ''):
520 """Toggle autoindent on/off (if available)."""
520 """Toggle autoindent on/off (if available)."""
521
521
522 self.shell.set_autoindent()
522 self.shell.set_autoindent()
523 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
523 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
524
524
525
525
526 def magic_automagic(self, parameter_s = ''):
526 def magic_automagic(self, parameter_s = ''):
527 """Make magic functions callable without having to type the initial %.
527 """Make magic functions callable without having to type the initial %.
528
528
529 Without argumentsl toggles on/off (when off, you must call it as
529 Without argumentsl toggles on/off (when off, you must call it as
530 %automagic, of course). With arguments it sets the value, and you can
530 %automagic, of course). With arguments it sets the value, and you can
531 use any of (case insensitive):
531 use any of (case insensitive):
532
532
533 - on,1,True: to activate
533 - on,1,True: to activate
534
534
535 - off,0,False: to deactivate.
535 - off,0,False: to deactivate.
536
536
537 Note that magic functions have lowest priority, so if there's a
537 Note that magic functions have lowest priority, so if there's a
538 variable whose name collides with that of a magic fn, automagic won't
538 variable whose name collides with that of a magic fn, automagic won't
539 work for that function (you get the variable instead). However, if you
539 work for that function (you get the variable instead). However, if you
540 delete the variable (del var), the previously shadowed magic function
540 delete the variable (del var), the previously shadowed magic function
541 becomes visible to automagic again."""
541 becomes visible to automagic again."""
542
542
543 arg = parameter_s.lower()
543 arg = parameter_s.lower()
544 if parameter_s in ('on','1','true'):
544 if parameter_s in ('on','1','true'):
545 self.shell.automagic = True
545 self.shell.automagic = True
546 elif parameter_s in ('off','0','false'):
546 elif parameter_s in ('off','0','false'):
547 self.shell.automagic = False
547 self.shell.automagic = False
548 else:
548 else:
549 self.shell.automagic = not self.shell.automagic
549 self.shell.automagic = not self.shell.automagic
550 print '\n' + Magic.auto_status[self.shell.automagic]
550 print '\n' + Magic.auto_status[self.shell.automagic]
551
551
552 @testdec.skip_doctest
552 @testdec.skip_doctest
553 def magic_autocall(self, parameter_s = ''):
553 def magic_autocall(self, parameter_s = ''):
554 """Make functions callable without having to type parentheses.
554 """Make functions callable without having to type parentheses.
555
555
556 Usage:
556 Usage:
557
557
558 %autocall [mode]
558 %autocall [mode]
559
559
560 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
560 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
561 value is toggled on and off (remembering the previous state).
561 value is toggled on and off (remembering the previous state).
562
562
563 In more detail, these values mean:
563 In more detail, these values mean:
564
564
565 0 -> fully disabled
565 0 -> fully disabled
566
566
567 1 -> active, but do not apply if there are no arguments on the line.
567 1 -> active, but do not apply if there are no arguments on the line.
568
568
569 In this mode, you get:
569 In this mode, you get:
570
570
571 In [1]: callable
571 In [1]: callable
572 Out[1]: <built-in function callable>
572 Out[1]: <built-in function callable>
573
573
574 In [2]: callable 'hello'
574 In [2]: callable 'hello'
575 ------> callable('hello')
575 ------> callable('hello')
576 Out[2]: False
576 Out[2]: False
577
577
578 2 -> Active always. Even if no arguments are present, the callable
578 2 -> Active always. Even if no arguments are present, the callable
579 object is called:
579 object is called:
580
580
581 In [2]: float
581 In [2]: float
582 ------> float()
582 ------> float()
583 Out[2]: 0.0
583 Out[2]: 0.0
584
584
585 Note that even with autocall off, you can still use '/' at the start of
585 Note that even with autocall off, you can still use '/' at the start of
586 a line to treat the first argument on the command line as a function
586 a line to treat the first argument on the command line as a function
587 and add parentheses to it:
587 and add parentheses to it:
588
588
589 In [8]: /str 43
589 In [8]: /str 43
590 ------> str(43)
590 ------> str(43)
591 Out[8]: '43'
591 Out[8]: '43'
592
592
593 # all-random (note for auto-testing)
593 # all-random (note for auto-testing)
594 """
594 """
595
595
596 if parameter_s:
596 if parameter_s:
597 arg = int(parameter_s)
597 arg = int(parameter_s)
598 else:
598 else:
599 arg = 'toggle'
599 arg = 'toggle'
600
600
601 if not arg in (0,1,2,'toggle'):
601 if not arg in (0,1,2,'toggle'):
602 error('Valid modes: (0->Off, 1->Smart, 2->Full')
602 error('Valid modes: (0->Off, 1->Smart, 2->Full')
603 return
603 return
604
604
605 if arg in (0,1,2):
605 if arg in (0,1,2):
606 self.shell.autocall = arg
606 self.shell.autocall = arg
607 else: # toggle
607 else: # toggle
608 if self.shell.autocall:
608 if self.shell.autocall:
609 self._magic_state.autocall_save = self.shell.autocall
609 self._magic_state.autocall_save = self.shell.autocall
610 self.shell.autocall = 0
610 self.shell.autocall = 0
611 else:
611 else:
612 try:
612 try:
613 self.shell.autocall = self._magic_state.autocall_save
613 self.shell.autocall = self._magic_state.autocall_save
614 except AttributeError:
614 except AttributeError:
615 self.shell.autocall = self._magic_state.autocall_save = 1
615 self.shell.autocall = self._magic_state.autocall_save = 1
616
616
617 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
617 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
618
618
619 def magic_system_verbose(self, parameter_s = ''):
619 def magic_system_verbose(self, parameter_s = ''):
620 """Set verbose printing of system calls.
620 """Set verbose printing of system calls.
621
621
622 If called without an argument, act as a toggle"""
622 If called without an argument, act as a toggle"""
623
623
624 if parameter_s:
624 if parameter_s:
625 val = bool(eval(parameter_s))
625 val = bool(eval(parameter_s))
626 else:
626 else:
627 val = None
627 val = None
628
628
629 if self.shell.system_verbose:
629 if self.shell.system_verbose:
630 self.shell.system_verbose = False
630 self.shell.system_verbose = False
631 else:
631 else:
632 self.shell.system_verbose = True
632 self.shell.system_verbose = True
633 print "System verbose printing is:",\
633 print "System verbose printing is:",\
634 ['OFF','ON'][self.shell.system_verbose]
634 ['OFF','ON'][self.shell.system_verbose]
635
635
636
636
637 def magic_page(self, parameter_s=''):
637 def magic_page(self, parameter_s=''):
638 """Pretty print the object and display it through a pager.
638 """Pretty print the object and display it through a pager.
639
639
640 %page [options] OBJECT
640 %page [options] OBJECT
641
641
642 If no object is given, use _ (last output).
642 If no object is given, use _ (last output).
643
643
644 Options:
644 Options:
645
645
646 -r: page str(object), don't pretty-print it."""
646 -r: page str(object), don't pretty-print it."""
647
647
648 # After a function contributed by Olivier Aubert, slightly modified.
648 # After a function contributed by Olivier Aubert, slightly modified.
649
649
650 # Process options/args
650 # Process options/args
651 opts,args = self.parse_options(parameter_s,'r')
651 opts,args = self.parse_options(parameter_s,'r')
652 raw = 'r' in opts
652 raw = 'r' in opts
653
653
654 oname = args and args or '_'
654 oname = args and args or '_'
655 info = self._ofind(oname)
655 info = self._ofind(oname)
656 if info['found']:
656 if info['found']:
657 txt = (raw and str or pformat)( info['obj'] )
657 txt = (raw and str or pformat)( info['obj'] )
658 page(txt)
658 page(txt)
659 else:
659 else:
660 print 'Object `%s` not found' % oname
660 print 'Object `%s` not found' % oname
661
661
662 def magic_profile(self, parameter_s=''):
662 def magic_profile(self, parameter_s=''):
663 """Print your currently active IPython profile."""
663 """Print your currently active IPython profile."""
664 if self.shell.profile:
664 if self.shell.profile:
665 printpl('Current IPython profile: $self.shell.profile.')
665 printpl('Current IPython profile: $self.shell.profile.')
666 else:
666 else:
667 print 'No profile active.'
667 print 'No profile active.'
668
668
669 def magic_pinfo(self, parameter_s='', namespaces=None):
669 def magic_pinfo(self, parameter_s='', namespaces=None):
670 """Provide detailed information about an object.
670 """Provide detailed information about an object.
671
671
672 '%pinfo object' is just a synonym for object? or ?object."""
672 '%pinfo object' is just a synonym for object? or ?object."""
673
673
674 #print 'pinfo par: <%s>' % parameter_s # dbg
674 #print 'pinfo par: <%s>' % parameter_s # dbg
675
675
676
676
677 # detail_level: 0 -> obj? , 1 -> obj??
677 # detail_level: 0 -> obj? , 1 -> obj??
678 detail_level = 0
678 detail_level = 0
679 # We need to detect if we got called as 'pinfo pinfo foo', which can
679 # We need to detect if we got called as 'pinfo pinfo foo', which can
680 # happen if the user types 'pinfo foo?' at the cmd line.
680 # happen if the user types 'pinfo foo?' at the cmd line.
681 pinfo,qmark1,oname,qmark2 = \
681 pinfo,qmark1,oname,qmark2 = \
682 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
682 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
683 if pinfo or qmark1 or qmark2:
683 if pinfo or qmark1 or qmark2:
684 detail_level = 1
684 detail_level = 1
685 if "*" in oname:
685 if "*" in oname:
686 self.magic_psearch(oname)
686 self.magic_psearch(oname)
687 else:
687 else:
688 self._inspect('pinfo', oname, detail_level=detail_level,
688 self._inspect('pinfo', oname, detail_level=detail_level,
689 namespaces=namespaces)
689 namespaces=namespaces)
690
690
691 def magic_pdef(self, parameter_s='', namespaces=None):
691 def magic_pdef(self, parameter_s='', namespaces=None):
692 """Print the definition header for any callable object.
692 """Print the definition header for any callable object.
693
693
694 If the object is a class, print the constructor information."""
694 If the object is a class, print the constructor information."""
695 self._inspect('pdef',parameter_s, namespaces)
695 self._inspect('pdef',parameter_s, namespaces)
696
696
697 def magic_pdoc(self, parameter_s='', namespaces=None):
697 def magic_pdoc(self, parameter_s='', namespaces=None):
698 """Print the docstring for an object.
698 """Print the docstring for an object.
699
699
700 If the given object is a class, it will print both the class and the
700 If the given object is a class, it will print both the class and the
701 constructor docstrings."""
701 constructor docstrings."""
702 self._inspect('pdoc',parameter_s, namespaces)
702 self._inspect('pdoc',parameter_s, namespaces)
703
703
704 def magic_psource(self, parameter_s='', namespaces=None):
704 def magic_psource(self, parameter_s='', namespaces=None):
705 """Print (or run through pager) the source code for an object."""
705 """Print (or run through pager) the source code for an object."""
706 self._inspect('psource',parameter_s, namespaces)
706 self._inspect('psource',parameter_s, namespaces)
707
707
708 def magic_pfile(self, parameter_s=''):
708 def magic_pfile(self, parameter_s=''):
709 """Print (or run through pager) the file where an object is defined.
709 """Print (or run through pager) the file where an object is defined.
710
710
711 The file opens at the line where the object definition begins. IPython
711 The file opens at the line where the object definition begins. IPython
712 will honor the environment variable PAGER if set, and otherwise will
712 will honor the environment variable PAGER if set, and otherwise will
713 do its best to print the file in a convenient form.
713 do its best to print the file in a convenient form.
714
714
715 If the given argument is not an object currently defined, IPython will
715 If the given argument is not an object currently defined, IPython will
716 try to interpret it as a filename (automatically adding a .py extension
716 try to interpret it as a filename (automatically adding a .py extension
717 if needed). You can thus use %pfile as a syntax highlighting code
717 if needed). You can thus use %pfile as a syntax highlighting code
718 viewer."""
718 viewer."""
719
719
720 # first interpret argument as an object name
720 # first interpret argument as an object name
721 out = self._inspect('pfile',parameter_s)
721 out = self._inspect('pfile',parameter_s)
722 # if not, try the input as a filename
722 # if not, try the input as a filename
723 if out == 'not found':
723 if out == 'not found':
724 try:
724 try:
725 filename = get_py_filename(parameter_s)
725 filename = get_py_filename(parameter_s)
726 except IOError,msg:
726 except IOError,msg:
727 print msg
727 print msg
728 return
728 return
729 page(self.shell.inspector.format(file(filename).read()))
729 page(self.shell.inspector.format(file(filename).read()))
730
730
731 def _inspect(self,meth,oname,namespaces=None,**kw):
731 def _inspect(self,meth,oname,namespaces=None,**kw):
732 """Generic interface to the inspector system.
732 """Generic interface to the inspector system.
733
733
734 This function is meant to be called by pdef, pdoc & friends."""
734 This function is meant to be called by pdef, pdoc & friends."""
735
735
736 #oname = oname.strip()
736 #oname = oname.strip()
737 #print '1- oname: <%r>' % oname # dbg
737 #print '1- oname: <%r>' % oname # dbg
738 try:
738 try:
739 oname = oname.strip().encode('ascii')
739 oname = oname.strip().encode('ascii')
740 #print '2- oname: <%r>' % oname # dbg
740 #print '2- oname: <%r>' % oname # dbg
741 except UnicodeEncodeError:
741 except UnicodeEncodeError:
742 print 'Python identifiers can only contain ascii characters.'
742 print 'Python identifiers can only contain ascii characters.'
743 return 'not found'
743 return 'not found'
744
744
745 info = Struct(self._ofind(oname, namespaces))
745 info = Struct(self._ofind(oname, namespaces))
746
746
747 if info.found:
747 if info.found:
748 try:
748 try:
749 IPython.utils.generics.inspect_object(info.obj)
749 IPython.utils.generics.inspect_object(info.obj)
750 return
750 return
751 except TryNext:
751 except TryNext:
752 pass
752 pass
753 # Get the docstring of the class property if it exists.
753 # Get the docstring of the class property if it exists.
754 path = oname.split('.')
754 path = oname.split('.')
755 root = '.'.join(path[:-1])
755 root = '.'.join(path[:-1])
756 if info.parent is not None:
756 if info.parent is not None:
757 try:
757 try:
758 target = getattr(info.parent, '__class__')
758 target = getattr(info.parent, '__class__')
759 # The object belongs to a class instance.
759 # The object belongs to a class instance.
760 try:
760 try:
761 target = getattr(target, path[-1])
761 target = getattr(target, path[-1])
762 # The class defines the object.
762 # The class defines the object.
763 if isinstance(target, property):
763 if isinstance(target, property):
764 oname = root + '.__class__.' + path[-1]
764 oname = root + '.__class__.' + path[-1]
765 info = Struct(self._ofind(oname))
765 info = Struct(self._ofind(oname))
766 except AttributeError: pass
766 except AttributeError: pass
767 except AttributeError: pass
767 except AttributeError: pass
768
768
769 pmethod = getattr(self.shell.inspector,meth)
769 pmethod = getattr(self.shell.inspector,meth)
770 formatter = info.ismagic and self.format_screen or None
770 formatter = info.ismagic and self.format_screen or None
771 if meth == 'pdoc':
771 if meth == 'pdoc':
772 pmethod(info.obj,oname,formatter)
772 pmethod(info.obj,oname,formatter)
773 elif meth == 'pinfo':
773 elif meth == 'pinfo':
774 pmethod(info.obj,oname,formatter,info,**kw)
774 pmethod(info.obj,oname,formatter,info,**kw)
775 else:
775 else:
776 pmethod(info.obj,oname)
776 pmethod(info.obj,oname)
777 else:
777 else:
778 print 'Object `%s` not found.' % oname
778 print 'Object `%s` not found.' % oname
779 return 'not found' # so callers can take other action
779 return 'not found' # so callers can take other action
780
780
781 def magic_psearch(self, parameter_s=''):
781 def magic_psearch(self, parameter_s=''):
782 """Search for object in namespaces by wildcard.
782 """Search for object in namespaces by wildcard.
783
783
784 %psearch [options] PATTERN [OBJECT TYPE]
784 %psearch [options] PATTERN [OBJECT TYPE]
785
785
786 Note: ? can be used as a synonym for %psearch, at the beginning or at
786 Note: ? can be used as a synonym for %psearch, at the beginning or at
787 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
787 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
788 rest of the command line must be unchanged (options come first), so
788 rest of the command line must be unchanged (options come first), so
789 for example the following forms are equivalent
789 for example the following forms are equivalent
790
790
791 %psearch -i a* function
791 %psearch -i a* function
792 -i a* function?
792 -i a* function?
793 ?-i a* function
793 ?-i a* function
794
794
795 Arguments:
795 Arguments:
796
796
797 PATTERN
797 PATTERN
798
798
799 where PATTERN is a string containing * as a wildcard similar to its
799 where PATTERN is a string containing * as a wildcard similar to its
800 use in a shell. The pattern is matched in all namespaces on the
800 use in a shell. The pattern is matched in all namespaces on the
801 search path. By default objects starting with a single _ are not
801 search path. By default objects starting with a single _ are not
802 matched, many IPython generated objects have a single
802 matched, many IPython generated objects have a single
803 underscore. The default is case insensitive matching. Matching is
803 underscore. The default is case insensitive matching. Matching is
804 also done on the attributes of objects and not only on the objects
804 also done on the attributes of objects and not only on the objects
805 in a module.
805 in a module.
806
806
807 [OBJECT TYPE]
807 [OBJECT TYPE]
808
808
809 Is the name of a python type from the types module. The name is
809 Is the name of a python type from the types module. The name is
810 given in lowercase without the ending type, ex. StringType is
810 given in lowercase without the ending type, ex. StringType is
811 written string. By adding a type here only objects matching the
811 written string. By adding a type here only objects matching the
812 given type are matched. Using all here makes the pattern match all
812 given type are matched. Using all here makes the pattern match all
813 types (this is the default).
813 types (this is the default).
814
814
815 Options:
815 Options:
816
816
817 -a: makes the pattern match even objects whose names start with a
817 -a: makes the pattern match even objects whose names start with a
818 single underscore. These names are normally ommitted from the
818 single underscore. These names are normally ommitted from the
819 search.
819 search.
820
820
821 -i/-c: make the pattern case insensitive/sensitive. If neither of
821 -i/-c: make the pattern case insensitive/sensitive. If neither of
822 these options is given, the default is read from your ipythonrc
822 these options is given, the default is read from your ipythonrc
823 file. The option name which sets this value is
823 file. The option name which sets this value is
824 'wildcards_case_sensitive'. If this option is not specified in your
824 'wildcards_case_sensitive'. If this option is not specified in your
825 ipythonrc file, IPython's internal default is to do a case sensitive
825 ipythonrc file, IPython's internal default is to do a case sensitive
826 search.
826 search.
827
827
828 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
828 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
829 specifiy can be searched in any of the following namespaces:
829 specifiy can be searched in any of the following namespaces:
830 'builtin', 'user', 'user_global','internal', 'alias', where
830 'builtin', 'user', 'user_global','internal', 'alias', where
831 'builtin' and 'user' are the search defaults. Note that you should
831 'builtin' and 'user' are the search defaults. Note that you should
832 not use quotes when specifying namespaces.
832 not use quotes when specifying namespaces.
833
833
834 'Builtin' contains the python module builtin, 'user' contains all
834 'Builtin' contains the python module builtin, 'user' contains all
835 user data, 'alias' only contain the shell aliases and no python
835 user data, 'alias' only contain the shell aliases and no python
836 objects, 'internal' contains objects used by IPython. The
836 objects, 'internal' contains objects used by IPython. The
837 'user_global' namespace is only used by embedded IPython instances,
837 'user_global' namespace is only used by embedded IPython instances,
838 and it contains module-level globals. You can add namespaces to the
838 and it contains module-level globals. You can add namespaces to the
839 search with -s or exclude them with -e (these options can be given
839 search with -s or exclude them with -e (these options can be given
840 more than once).
840 more than once).
841
841
842 Examples:
842 Examples:
843
843
844 %psearch a* -> objects beginning with an a
844 %psearch a* -> objects beginning with an a
845 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
845 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
846 %psearch a* function -> all functions beginning with an a
846 %psearch a* function -> all functions beginning with an a
847 %psearch re.e* -> objects beginning with an e in module re
847 %psearch re.e* -> objects beginning with an e in module re
848 %psearch r*.e* -> objects that start with e in modules starting in r
848 %psearch r*.e* -> objects that start with e in modules starting in r
849 %psearch r*.* string -> all strings in modules beginning with r
849 %psearch r*.* string -> all strings in modules beginning with r
850
850
851 Case sensitve search:
851 Case sensitve search:
852
852
853 %psearch -c a* list all object beginning with lower case a
853 %psearch -c a* list all object beginning with lower case a
854
854
855 Show objects beginning with a single _:
855 Show objects beginning with a single _:
856
856
857 %psearch -a _* list objects beginning with a single underscore"""
857 %psearch -a _* list objects beginning with a single underscore"""
858 try:
858 try:
859 parameter_s = parameter_s.encode('ascii')
859 parameter_s = parameter_s.encode('ascii')
860 except UnicodeEncodeError:
860 except UnicodeEncodeError:
861 print 'Python identifiers can only contain ascii characters.'
861 print 'Python identifiers can only contain ascii characters.'
862 return
862 return
863
863
864 # default namespaces to be searched
864 # default namespaces to be searched
865 def_search = ['user','builtin']
865 def_search = ['user','builtin']
866
866
867 # Process options/args
867 # Process options/args
868 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
868 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
869 opt = opts.get
869 opt = opts.get
870 shell = self.shell
870 shell = self.shell
871 psearch = shell.inspector.psearch
871 psearch = shell.inspector.psearch
872
872
873 # select case options
873 # select case options
874 if opts.has_key('i'):
874 if opts.has_key('i'):
875 ignore_case = True
875 ignore_case = True
876 elif opts.has_key('c'):
876 elif opts.has_key('c'):
877 ignore_case = False
877 ignore_case = False
878 else:
878 else:
879 ignore_case = not shell.wildcards_case_sensitive
879 ignore_case = not shell.wildcards_case_sensitive
880
880
881 # Build list of namespaces to search from user options
881 # Build list of namespaces to search from user options
882 def_search.extend(opt('s',[]))
882 def_search.extend(opt('s',[]))
883 ns_exclude = ns_exclude=opt('e',[])
883 ns_exclude = ns_exclude=opt('e',[])
884 ns_search = [nm for nm in def_search if nm not in ns_exclude]
884 ns_search = [nm for nm in def_search if nm not in ns_exclude]
885
885
886 # Call the actual search
886 # Call the actual search
887 try:
887 try:
888 psearch(args,shell.ns_table,ns_search,
888 psearch(args,shell.ns_table,ns_search,
889 show_all=opt('a'),ignore_case=ignore_case)
889 show_all=opt('a'),ignore_case=ignore_case)
890 except:
890 except:
891 shell.showtraceback()
891 shell.showtraceback()
892
892
893 def magic_who_ls(self, parameter_s=''):
893 def magic_who_ls(self, parameter_s=''):
894 """Return a sorted list of all interactive variables.
894 """Return a sorted list of all interactive variables.
895
895
896 If arguments are given, only variables of types matching these
896 If arguments are given, only variables of types matching these
897 arguments are returned."""
897 arguments are returned."""
898
898
899 user_ns = self.shell.user_ns
899 user_ns = self.shell.user_ns
900 internal_ns = self.shell.internal_ns
900 internal_ns = self.shell.internal_ns
901 user_ns_hidden = self.shell.user_ns_hidden
901 user_ns_hidden = self.shell.user_ns_hidden
902 out = [ i for i in user_ns
902 out = [ i for i in user_ns
903 if not i.startswith('_') \
903 if not i.startswith('_') \
904 and not (i in internal_ns or i in user_ns_hidden) ]
904 and not (i in internal_ns or i in user_ns_hidden) ]
905
905
906 typelist = parameter_s.split()
906 typelist = parameter_s.split()
907 if typelist:
907 if typelist:
908 typeset = set(typelist)
908 typeset = set(typelist)
909 out = [i for i in out if type(i).__name__ in typeset]
909 out = [i for i in out if type(i).__name__ in typeset]
910
910
911 out.sort()
911 out.sort()
912 return out
912 return out
913
913
914 def magic_who(self, parameter_s=''):
914 def magic_who(self, parameter_s=''):
915 """Print all interactive variables, with some minimal formatting.
915 """Print all interactive variables, with some minimal formatting.
916
916
917 If any arguments are given, only variables whose type matches one of
917 If any arguments are given, only variables whose type matches one of
918 these are printed. For example:
918 these are printed. For example:
919
919
920 %who function str
920 %who function str
921
921
922 will only list functions and strings, excluding all other types of
922 will only list functions and strings, excluding all other types of
923 variables. To find the proper type names, simply use type(var) at a
923 variables. To find the proper type names, simply use type(var) at a
924 command line to see how python prints type names. For example:
924 command line to see how python prints type names. For example:
925
925
926 In [1]: type('hello')\\
926 In [1]: type('hello')\\
927 Out[1]: <type 'str'>
927 Out[1]: <type 'str'>
928
928
929 indicates that the type name for strings is 'str'.
929 indicates that the type name for strings is 'str'.
930
930
931 %who always excludes executed names loaded through your configuration
931 %who always excludes executed names loaded through your configuration
932 file and things which are internal to IPython.
932 file and things which are internal to IPython.
933
933
934 This is deliberate, as typically you may load many modules and the
934 This is deliberate, as typically you may load many modules and the
935 purpose of %who is to show you only what you've manually defined."""
935 purpose of %who is to show you only what you've manually defined."""
936
936
937 varlist = self.magic_who_ls(parameter_s)
937 varlist = self.magic_who_ls(parameter_s)
938 if not varlist:
938 if not varlist:
939 if parameter_s:
939 if parameter_s:
940 print 'No variables match your requested type.'
940 print 'No variables match your requested type.'
941 else:
941 else:
942 print 'Interactive namespace is empty.'
942 print 'Interactive namespace is empty.'
943 return
943 return
944
944
945 # if we have variables, move on...
945 # if we have variables, move on...
946 count = 0
946 count = 0
947 for i in varlist:
947 for i in varlist:
948 print i+'\t',
948 print i+'\t',
949 count += 1
949 count += 1
950 if count > 8:
950 if count > 8:
951 count = 0
951 count = 0
952 print
952 print
953 print
953 print
954
954
955 def magic_whos(self, parameter_s=''):
955 def magic_whos(self, parameter_s=''):
956 """Like %who, but gives some extra information about each variable.
956 """Like %who, but gives some extra information about each variable.
957
957
958 The same type filtering of %who can be applied here.
958 The same type filtering of %who can be applied here.
959
959
960 For all variables, the type is printed. Additionally it prints:
960 For all variables, the type is printed. Additionally it prints:
961
961
962 - For {},[],(): their length.
962 - For {},[],(): their length.
963
963
964 - For numpy and Numeric arrays, a summary with shape, number of
964 - For numpy and Numeric arrays, a summary with shape, number of
965 elements, typecode and size in memory.
965 elements, typecode and size in memory.
966
966
967 - Everything else: a string representation, snipping their middle if
967 - Everything else: a string representation, snipping their middle if
968 too long."""
968 too long."""
969
969
970 varnames = self.magic_who_ls(parameter_s)
970 varnames = self.magic_who_ls(parameter_s)
971 if not varnames:
971 if not varnames:
972 if parameter_s:
972 if parameter_s:
973 print 'No variables match your requested type.'
973 print 'No variables match your requested type.'
974 else:
974 else:
975 print 'Interactive namespace is empty.'
975 print 'Interactive namespace is empty.'
976 return
976 return
977
977
978 # if we have variables, move on...
978 # if we have variables, move on...
979
979
980 # for these types, show len() instead of data:
980 # for these types, show len() instead of data:
981 seq_types = [types.DictType,types.ListType,types.TupleType]
981 seq_types = [types.DictType,types.ListType,types.TupleType]
982
982
983 # for numpy/Numeric arrays, display summary info
983 # for numpy/Numeric arrays, display summary info
984 try:
984 try:
985 import numpy
985 import numpy
986 except ImportError:
986 except ImportError:
987 ndarray_type = None
987 ndarray_type = None
988 else:
988 else:
989 ndarray_type = numpy.ndarray.__name__
989 ndarray_type = numpy.ndarray.__name__
990 try:
990 try:
991 import Numeric
991 import Numeric
992 except ImportError:
992 except ImportError:
993 array_type = None
993 array_type = None
994 else:
994 else:
995 array_type = Numeric.ArrayType.__name__
995 array_type = Numeric.ArrayType.__name__
996
996
997 # Find all variable names and types so we can figure out column sizes
997 # Find all variable names and types so we can figure out column sizes
998 def get_vars(i):
998 def get_vars(i):
999 return self.shell.user_ns[i]
999 return self.shell.user_ns[i]
1000
1000
1001 # some types are well known and can be shorter
1001 # some types are well known and can be shorter
1002 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
1002 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
1003 def type_name(v):
1003 def type_name(v):
1004 tn = type(v).__name__
1004 tn = type(v).__name__
1005 return abbrevs.get(tn,tn)
1005 return abbrevs.get(tn,tn)
1006
1006
1007 varlist = map(get_vars,varnames)
1007 varlist = map(get_vars,varnames)
1008
1008
1009 typelist = []
1009 typelist = []
1010 for vv in varlist:
1010 for vv in varlist:
1011 tt = type_name(vv)
1011 tt = type_name(vv)
1012
1012
1013 if tt=='instance':
1013 if tt=='instance':
1014 typelist.append( abbrevs.get(str(vv.__class__),
1014 typelist.append( abbrevs.get(str(vv.__class__),
1015 str(vv.__class__)))
1015 str(vv.__class__)))
1016 else:
1016 else:
1017 typelist.append(tt)
1017 typelist.append(tt)
1018
1018
1019 # column labels and # of spaces as separator
1019 # column labels and # of spaces as separator
1020 varlabel = 'Variable'
1020 varlabel = 'Variable'
1021 typelabel = 'Type'
1021 typelabel = 'Type'
1022 datalabel = 'Data/Info'
1022 datalabel = 'Data/Info'
1023 colsep = 3
1023 colsep = 3
1024 # variable format strings
1024 # variable format strings
1025 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
1025 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
1026 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
1026 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
1027 aformat = "%s: %s elems, type `%s`, %s bytes"
1027 aformat = "%s: %s elems, type `%s`, %s bytes"
1028 # find the size of the columns to format the output nicely
1028 # find the size of the columns to format the output nicely
1029 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
1029 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
1030 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
1030 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
1031 # table header
1031 # table header
1032 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
1032 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
1033 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
1033 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
1034 # and the table itself
1034 # and the table itself
1035 kb = 1024
1035 kb = 1024
1036 Mb = 1048576 # kb**2
1036 Mb = 1048576 # kb**2
1037 for vname,var,vtype in zip(varnames,varlist,typelist):
1037 for vname,var,vtype in zip(varnames,varlist,typelist):
1038 print itpl(vformat),
1038 print itpl(vformat),
1039 if vtype in seq_types:
1039 if vtype in seq_types:
1040 print len(var)
1040 print len(var)
1041 elif vtype in [array_type,ndarray_type]:
1041 elif vtype in [array_type,ndarray_type]:
1042 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
1042 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
1043 if vtype==ndarray_type:
1043 if vtype==ndarray_type:
1044 # numpy
1044 # numpy
1045 vsize = var.size
1045 vsize = var.size
1046 vbytes = vsize*var.itemsize
1046 vbytes = vsize*var.itemsize
1047 vdtype = var.dtype
1047 vdtype = var.dtype
1048 else:
1048 else:
1049 # Numeric
1049 # Numeric
1050 vsize = Numeric.size(var)
1050 vsize = Numeric.size(var)
1051 vbytes = vsize*var.itemsize()
1051 vbytes = vsize*var.itemsize()
1052 vdtype = var.typecode()
1052 vdtype = var.typecode()
1053
1053
1054 if vbytes < 100000:
1054 if vbytes < 100000:
1055 print aformat % (vshape,vsize,vdtype,vbytes)
1055 print aformat % (vshape,vsize,vdtype,vbytes)
1056 else:
1056 else:
1057 print aformat % (vshape,vsize,vdtype,vbytes),
1057 print aformat % (vshape,vsize,vdtype,vbytes),
1058 if vbytes < Mb:
1058 if vbytes < Mb:
1059 print '(%s kb)' % (vbytes/kb,)
1059 print '(%s kb)' % (vbytes/kb,)
1060 else:
1060 else:
1061 print '(%s Mb)' % (vbytes/Mb,)
1061 print '(%s Mb)' % (vbytes/Mb,)
1062 else:
1062 else:
1063 try:
1063 try:
1064 vstr = str(var)
1064 vstr = str(var)
1065 except UnicodeEncodeError:
1065 except UnicodeEncodeError:
1066 vstr = unicode(var).encode(sys.getdefaultencoding(),
1066 vstr = unicode(var).encode(sys.getdefaultencoding(),
1067 'backslashreplace')
1067 'backslashreplace')
1068 vstr = vstr.replace('\n','\\n')
1068 vstr = vstr.replace('\n','\\n')
1069 if len(vstr) < 50:
1069 if len(vstr) < 50:
1070 print vstr
1070 print vstr
1071 else:
1071 else:
1072 printpl(vfmt_short)
1072 printpl(vfmt_short)
1073
1073
1074 def magic_reset(self, parameter_s=''):
1074 def magic_reset(self, parameter_s=''):
1075 """Resets the namespace by removing all names defined by the user.
1075 """Resets the namespace by removing all names defined by the user.
1076
1076
1077 Input/Output history are left around in case you need them.
1077 Input/Output history are left around in case you need them.
1078
1078
1079 Parameters
1079 Parameters
1080 ----------
1080 ----------
1081 -y : force reset without asking for confirmation.
1081 -y : force reset without asking for confirmation.
1082
1082
1083 Examples
1083 Examples
1084 --------
1084 --------
1085 In [6]: a = 1
1085 In [6]: a = 1
1086
1086
1087 In [7]: a
1087 In [7]: a
1088 Out[7]: 1
1088 Out[7]: 1
1089
1089
1090 In [8]: 'a' in _ip.user_ns
1090 In [8]: 'a' in _ip.user_ns
1091 Out[8]: True
1091 Out[8]: True
1092
1092
1093 In [9]: %reset -f
1093 In [9]: %reset -f
1094
1094
1095 In [10]: 'a' in _ip.user_ns
1095 In [10]: 'a' in _ip.user_ns
1096 Out[10]: False
1096 Out[10]: False
1097 """
1097 """
1098
1098
1099 if parameter_s == '-f':
1099 if parameter_s == '-f':
1100 ans = True
1100 ans = True
1101 else:
1101 else:
1102 ans = self.shell.ask_yes_no(
1102 ans = self.shell.ask_yes_no(
1103 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1103 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1104 if not ans:
1104 if not ans:
1105 print 'Nothing done.'
1105 print 'Nothing done.'
1106 return
1106 return
1107 user_ns = self.shell.user_ns
1107 user_ns = self.shell.user_ns
1108 for i in self.magic_who_ls():
1108 for i in self.magic_who_ls():
1109 del(user_ns[i])
1109 del(user_ns[i])
1110
1110
1111 # Also flush the private list of module references kept for script
1111 # Also flush the private list of module references kept for script
1112 # execution protection
1112 # execution protection
1113 self.shell.clear_main_mod_cache()
1113 self.shell.clear_main_mod_cache()
1114
1114
1115 def magic_reset_selective(self, parameter_s=''):
1115 def magic_reset_selective(self, parameter_s=''):
1116 """Resets the namespace by removing names defined by the user.
1116 """Resets the namespace by removing names defined by the user.
1117
1117
1118 Input/Output history are left around in case you need them.
1118 Input/Output history are left around in case you need them.
1119
1119
1120 %reset_selective [-f] regex
1120 %reset_selective [-f] regex
1121
1121
1122 No action is taken if regex is not included
1122 No action is taken if regex is not included
1123
1123
1124 Options
1124 Options
1125 -f : force reset without asking for confirmation.
1125 -f : force reset without asking for confirmation.
1126
1126
1127 Examples
1127 Examples
1128 --------
1128 --------
1129
1130 We first fully reset the namespace so your output looks identical to
1131 this example for pedagogical reasons; in practice you do not need a
1132 full reset.
1129
1133
1130 In [1]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
1134 In [1]: %reset -f
1131
1135
1132 In [2]: who_ls
1136 Now, with a clean namespace we can make a few variables and use
1133 Out[2]: ['a', 'b', 'b1', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
1137 %reset_selective to only delete names that match our regexp:
1134
1138
1135 In [3]: %reset_selective -f b[2-3]m
1139 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
1136
1140
1137 In [4]: who_ls
1141 In [3]: who_ls
1138 Out[4]: ['a', 'b', 'b1', 'b1m', 'b2s', 'c']
1142 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
1139
1143
1140 In [5]: %reset_selective -f d
1144 In [4]: %reset_selective -f b[2-3]m
1141
1145
1142 In [6]: who_ls
1146 In [5]: who_ls
1143 Out[6]: ['a', 'b', 'b1', 'b1m', 'b2s', 'c']
1147 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1144
1148
1145 In [7]: %reset_selective -f c
1149 In [6]: %reset_selective -f d
1146
1147 In [8]: who_ls
1148 Out[8]:['a', 'b', 'b1', 'b1m', 'b2s']
1149
1150
1150 In [9]: %reset_selective -f b
1151 In [7]: who_ls
1151
1152 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1152 In [10]: who_ls
1153
1153 Out[10]: ['a']
1154 In [8]: %reset_selective -f c
1154
1155
1156 In [9]: who_ls
1157 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
1158
1159 In [10]: %reset_selective -f b
1160
1161 In [11]: who_ls
1162 Out[11]: ['a']
1155 """
1163 """
1156
1164
1157 opts, regex = self.parse_options(parameter_s,'f')
1165 opts, regex = self.parse_options(parameter_s,'f')
1158
1166
1159 if opts.has_key('f'):
1167 if opts.has_key('f'):
1160 ans = True
1168 ans = True
1161 else:
1169 else:
1162 ans = self.shell.ask_yes_no(
1170 ans = self.shell.ask_yes_no(
1163 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1171 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1164 if not ans:
1172 if not ans:
1165 print 'Nothing done.'
1173 print 'Nothing done.'
1166 return
1174 return
1167 user_ns = self.shell.user_ns
1175 user_ns = self.shell.user_ns
1168 if not regex:
1176 if not regex:
1169 print 'No regex pattern specified. Nothing done.'
1177 print 'No regex pattern specified. Nothing done.'
1170 return
1178 return
1171 else:
1179 else:
1172 try:
1180 try:
1173 m = re.compile(regex)
1181 m = re.compile(regex)
1174 except TypeError:
1182 except TypeError:
1175 raise TypeError('regex must be a string or compiled pattern')
1183 raise TypeError('regex must be a string or compiled pattern')
1176 for i in self.magic_who_ls():
1184 for i in self.magic_who_ls():
1177 if m.search(i):
1185 if m.search(i):
1178 del(user_ns[i])
1186 del(user_ns[i])
1179
1187
1180 def magic_logstart(self,parameter_s=''):
1188 def magic_logstart(self,parameter_s=''):
1181 """Start logging anywhere in a session.
1189 """Start logging anywhere in a session.
1182
1190
1183 %logstart [-o|-r|-t] [log_name [log_mode]]
1191 %logstart [-o|-r|-t] [log_name [log_mode]]
1184
1192
1185 If no name is given, it defaults to a file named 'ipython_log.py' in your
1193 If no name is given, it defaults to a file named 'ipython_log.py' in your
1186 current directory, in 'rotate' mode (see below).
1194 current directory, in 'rotate' mode (see below).
1187
1195
1188 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1196 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1189 history up to that point and then continues logging.
1197 history up to that point and then continues logging.
1190
1198
1191 %logstart takes a second optional parameter: logging mode. This can be one
1199 %logstart takes a second optional parameter: logging mode. This can be one
1192 of (note that the modes are given unquoted):\\
1200 of (note that the modes are given unquoted):\\
1193 append: well, that says it.\\
1201 append: well, that says it.\\
1194 backup: rename (if exists) to name~ and start name.\\
1202 backup: rename (if exists) to name~ and start name.\\
1195 global: single logfile in your home dir, appended to.\\
1203 global: single logfile in your home dir, appended to.\\
1196 over : overwrite existing log.\\
1204 over : overwrite existing log.\\
1197 rotate: create rotating logs name.1~, name.2~, etc.
1205 rotate: create rotating logs name.1~, name.2~, etc.
1198
1206
1199 Options:
1207 Options:
1200
1208
1201 -o: log also IPython's output. In this mode, all commands which
1209 -o: log also IPython's output. In this mode, all commands which
1202 generate an Out[NN] prompt are recorded to the logfile, right after
1210 generate an Out[NN] prompt are recorded to the logfile, right after
1203 their corresponding input line. The output lines are always
1211 their corresponding input line. The output lines are always
1204 prepended with a '#[Out]# ' marker, so that the log remains valid
1212 prepended with a '#[Out]# ' marker, so that the log remains valid
1205 Python code.
1213 Python code.
1206
1214
1207 Since this marker is always the same, filtering only the output from
1215 Since this marker is always the same, filtering only the output from
1208 a log is very easy, using for example a simple awk call:
1216 a log is very easy, using for example a simple awk call:
1209
1217
1210 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1218 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1211
1219
1212 -r: log 'raw' input. Normally, IPython's logs contain the processed
1220 -r: log 'raw' input. Normally, IPython's logs contain the processed
1213 input, so that user lines are logged in their final form, converted
1221 input, so that user lines are logged in their final form, converted
1214 into valid Python. For example, %Exit is logged as
1222 into valid Python. For example, %Exit is logged as
1215 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1223 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1216 exactly as typed, with no transformations applied.
1224 exactly as typed, with no transformations applied.
1217
1225
1218 -t: put timestamps before each input line logged (these are put in
1226 -t: put timestamps before each input line logged (these are put in
1219 comments)."""
1227 comments)."""
1220
1228
1221 opts,par = self.parse_options(parameter_s,'ort')
1229 opts,par = self.parse_options(parameter_s,'ort')
1222 log_output = 'o' in opts
1230 log_output = 'o' in opts
1223 log_raw_input = 'r' in opts
1231 log_raw_input = 'r' in opts
1224 timestamp = 't' in opts
1232 timestamp = 't' in opts
1225
1233
1226 logger = self.shell.logger
1234 logger = self.shell.logger
1227
1235
1228 # if no args are given, the defaults set in the logger constructor by
1236 # if no args are given, the defaults set in the logger constructor by
1229 # ipytohn remain valid
1237 # ipytohn remain valid
1230 if par:
1238 if par:
1231 try:
1239 try:
1232 logfname,logmode = par.split()
1240 logfname,logmode = par.split()
1233 except:
1241 except:
1234 logfname = par
1242 logfname = par
1235 logmode = 'backup'
1243 logmode = 'backup'
1236 else:
1244 else:
1237 logfname = logger.logfname
1245 logfname = logger.logfname
1238 logmode = logger.logmode
1246 logmode = logger.logmode
1239 # put logfname into rc struct as if it had been called on the command
1247 # put logfname into rc struct as if it had been called on the command
1240 # line, so it ends up saved in the log header Save it in case we need
1248 # line, so it ends up saved in the log header Save it in case we need
1241 # to restore it...
1249 # to restore it...
1242 old_logfile = self.shell.logfile
1250 old_logfile = self.shell.logfile
1243 if logfname:
1251 if logfname:
1244 logfname = os.path.expanduser(logfname)
1252 logfname = os.path.expanduser(logfname)
1245 self.shell.logfile = logfname
1253 self.shell.logfile = logfname
1246
1254
1247 loghead = '# IPython log file\n\n'
1255 loghead = '# IPython log file\n\n'
1248 try:
1256 try:
1249 started = logger.logstart(logfname,loghead,logmode,
1257 started = logger.logstart(logfname,loghead,logmode,
1250 log_output,timestamp,log_raw_input)
1258 log_output,timestamp,log_raw_input)
1251 except:
1259 except:
1252 self.shell.logfile = old_logfile
1260 self.shell.logfile = old_logfile
1253 warn("Couldn't start log: %s" % sys.exc_info()[1])
1261 warn("Couldn't start log: %s" % sys.exc_info()[1])
1254 else:
1262 else:
1255 # log input history up to this point, optionally interleaving
1263 # log input history up to this point, optionally interleaving
1256 # output if requested
1264 # output if requested
1257
1265
1258 if timestamp:
1266 if timestamp:
1259 # disable timestamping for the previous history, since we've
1267 # disable timestamping for the previous history, since we've
1260 # lost those already (no time machine here).
1268 # lost those already (no time machine here).
1261 logger.timestamp = False
1269 logger.timestamp = False
1262
1270
1263 if log_raw_input:
1271 if log_raw_input:
1264 input_hist = self.shell.input_hist_raw
1272 input_hist = self.shell.input_hist_raw
1265 else:
1273 else:
1266 input_hist = self.shell.input_hist
1274 input_hist = self.shell.input_hist
1267
1275
1268 if log_output:
1276 if log_output:
1269 log_write = logger.log_write
1277 log_write = logger.log_write
1270 output_hist = self.shell.output_hist
1278 output_hist = self.shell.output_hist
1271 for n in range(1,len(input_hist)-1):
1279 for n in range(1,len(input_hist)-1):
1272 log_write(input_hist[n].rstrip())
1280 log_write(input_hist[n].rstrip())
1273 if n in output_hist:
1281 if n in output_hist:
1274 log_write(repr(output_hist[n]),'output')
1282 log_write(repr(output_hist[n]),'output')
1275 else:
1283 else:
1276 logger.log_write(input_hist[1:])
1284 logger.log_write(input_hist[1:])
1277 if timestamp:
1285 if timestamp:
1278 # re-enable timestamping
1286 # re-enable timestamping
1279 logger.timestamp = True
1287 logger.timestamp = True
1280
1288
1281 print ('Activating auto-logging. '
1289 print ('Activating auto-logging. '
1282 'Current session state plus future input saved.')
1290 'Current session state plus future input saved.')
1283 logger.logstate()
1291 logger.logstate()
1284
1292
1285 def magic_logstop(self,parameter_s=''):
1293 def magic_logstop(self,parameter_s=''):
1286 """Fully stop logging and close log file.
1294 """Fully stop logging and close log file.
1287
1295
1288 In order to start logging again, a new %logstart call needs to be made,
1296 In order to start logging again, a new %logstart call needs to be made,
1289 possibly (though not necessarily) with a new filename, mode and other
1297 possibly (though not necessarily) with a new filename, mode and other
1290 options."""
1298 options."""
1291 self.logger.logstop()
1299 self.logger.logstop()
1292
1300
1293 def magic_logoff(self,parameter_s=''):
1301 def magic_logoff(self,parameter_s=''):
1294 """Temporarily stop logging.
1302 """Temporarily stop logging.
1295
1303
1296 You must have previously started logging."""
1304 You must have previously started logging."""
1297 self.shell.logger.switch_log(0)
1305 self.shell.logger.switch_log(0)
1298
1306
1299 def magic_logon(self,parameter_s=''):
1307 def magic_logon(self,parameter_s=''):
1300 """Restart logging.
1308 """Restart logging.
1301
1309
1302 This function is for restarting logging which you've temporarily
1310 This function is for restarting logging which you've temporarily
1303 stopped with %logoff. For starting logging for the first time, you
1311 stopped with %logoff. For starting logging for the first time, you
1304 must use the %logstart function, which allows you to specify an
1312 must use the %logstart function, which allows you to specify an
1305 optional log filename."""
1313 optional log filename."""
1306
1314
1307 self.shell.logger.switch_log(1)
1315 self.shell.logger.switch_log(1)
1308
1316
1309 def magic_logstate(self,parameter_s=''):
1317 def magic_logstate(self,parameter_s=''):
1310 """Print the status of the logging system."""
1318 """Print the status of the logging system."""
1311
1319
1312 self.shell.logger.logstate()
1320 self.shell.logger.logstate()
1313
1321
1314 def magic_pdb(self, parameter_s=''):
1322 def magic_pdb(self, parameter_s=''):
1315 """Control the automatic calling of the pdb interactive debugger.
1323 """Control the automatic calling of the pdb interactive debugger.
1316
1324
1317 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1325 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1318 argument it works as a toggle.
1326 argument it works as a toggle.
1319
1327
1320 When an exception is triggered, IPython can optionally call the
1328 When an exception is triggered, IPython can optionally call the
1321 interactive pdb debugger after the traceback printout. %pdb toggles
1329 interactive pdb debugger after the traceback printout. %pdb toggles
1322 this feature on and off.
1330 this feature on and off.
1323
1331
1324 The initial state of this feature is set in your ipythonrc
1332 The initial state of this feature is set in your ipythonrc
1325 configuration file (the variable is called 'pdb').
1333 configuration file (the variable is called 'pdb').
1326
1334
1327 If you want to just activate the debugger AFTER an exception has fired,
1335 If you want to just activate the debugger AFTER an exception has fired,
1328 without having to type '%pdb on' and rerunning your code, you can use
1336 without having to type '%pdb on' and rerunning your code, you can use
1329 the %debug magic."""
1337 the %debug magic."""
1330
1338
1331 par = parameter_s.strip().lower()
1339 par = parameter_s.strip().lower()
1332
1340
1333 if par:
1341 if par:
1334 try:
1342 try:
1335 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1343 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1336 except KeyError:
1344 except KeyError:
1337 print ('Incorrect argument. Use on/1, off/0, '
1345 print ('Incorrect argument. Use on/1, off/0, '
1338 'or nothing for a toggle.')
1346 'or nothing for a toggle.')
1339 return
1347 return
1340 else:
1348 else:
1341 # toggle
1349 # toggle
1342 new_pdb = not self.shell.call_pdb
1350 new_pdb = not self.shell.call_pdb
1343
1351
1344 # set on the shell
1352 # set on the shell
1345 self.shell.call_pdb = new_pdb
1353 self.shell.call_pdb = new_pdb
1346 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1354 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1347
1355
1348 def magic_debug(self, parameter_s=''):
1356 def magic_debug(self, parameter_s=''):
1349 """Activate the interactive debugger in post-mortem mode.
1357 """Activate the interactive debugger in post-mortem mode.
1350
1358
1351 If an exception has just occurred, this lets you inspect its stack
1359 If an exception has just occurred, this lets you inspect its stack
1352 frames interactively. Note that this will always work only on the last
1360 frames interactively. Note that this will always work only on the last
1353 traceback that occurred, so you must call this quickly after an
1361 traceback that occurred, so you must call this quickly after an
1354 exception that you wish to inspect has fired, because if another one
1362 exception that you wish to inspect has fired, because if another one
1355 occurs, it clobbers the previous one.
1363 occurs, it clobbers the previous one.
1356
1364
1357 If you want IPython to automatically do this on every exception, see
1365 If you want IPython to automatically do this on every exception, see
1358 the %pdb magic for more details.
1366 the %pdb magic for more details.
1359 """
1367 """
1360 self.shell.debugger(force=True)
1368 self.shell.debugger(force=True)
1361
1369
1362 @testdec.skip_doctest
1370 @testdec.skip_doctest
1363 def magic_prun(self, parameter_s ='',user_mode=1,
1371 def magic_prun(self, parameter_s ='',user_mode=1,
1364 opts=None,arg_lst=None,prog_ns=None):
1372 opts=None,arg_lst=None,prog_ns=None):
1365
1373
1366 """Run a statement through the python code profiler.
1374 """Run a statement through the python code profiler.
1367
1375
1368 Usage:
1376 Usage:
1369 %prun [options] statement
1377 %prun [options] statement
1370
1378
1371 The given statement (which doesn't require quote marks) is run via the
1379 The given statement (which doesn't require quote marks) is run via the
1372 python profiler in a manner similar to the profile.run() function.
1380 python profiler in a manner similar to the profile.run() function.
1373 Namespaces are internally managed to work correctly; profile.run
1381 Namespaces are internally managed to work correctly; profile.run
1374 cannot be used in IPython because it makes certain assumptions about
1382 cannot be used in IPython because it makes certain assumptions about
1375 namespaces which do not hold under IPython.
1383 namespaces which do not hold under IPython.
1376
1384
1377 Options:
1385 Options:
1378
1386
1379 -l <limit>: you can place restrictions on what or how much of the
1387 -l <limit>: you can place restrictions on what or how much of the
1380 profile gets printed. The limit value can be:
1388 profile gets printed. The limit value can be:
1381
1389
1382 * A string: only information for function names containing this string
1390 * A string: only information for function names containing this string
1383 is printed.
1391 is printed.
1384
1392
1385 * An integer: only these many lines are printed.
1393 * An integer: only these many lines are printed.
1386
1394
1387 * A float (between 0 and 1): this fraction of the report is printed
1395 * A float (between 0 and 1): this fraction of the report is printed
1388 (for example, use a limit of 0.4 to see the topmost 40% only).
1396 (for example, use a limit of 0.4 to see the topmost 40% only).
1389
1397
1390 You can combine several limits with repeated use of the option. For
1398 You can combine several limits with repeated use of the option. For
1391 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1399 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1392 information about class constructors.
1400 information about class constructors.
1393
1401
1394 -r: return the pstats.Stats object generated by the profiling. This
1402 -r: return the pstats.Stats object generated by the profiling. This
1395 object has all the information about the profile in it, and you can
1403 object has all the information about the profile in it, and you can
1396 later use it for further analysis or in other functions.
1404 later use it for further analysis or in other functions.
1397
1405
1398 -s <key>: sort profile by given key. You can provide more than one key
1406 -s <key>: sort profile by given key. You can provide more than one key
1399 by using the option several times: '-s key1 -s key2 -s key3...'. The
1407 by using the option several times: '-s key1 -s key2 -s key3...'. The
1400 default sorting key is 'time'.
1408 default sorting key is 'time'.
1401
1409
1402 The following is copied verbatim from the profile documentation
1410 The following is copied verbatim from the profile documentation
1403 referenced below:
1411 referenced below:
1404
1412
1405 When more than one key is provided, additional keys are used as
1413 When more than one key is provided, additional keys are used as
1406 secondary criteria when the there is equality in all keys selected
1414 secondary criteria when the there is equality in all keys selected
1407 before them.
1415 before them.
1408
1416
1409 Abbreviations can be used for any key names, as long as the
1417 Abbreviations can be used for any key names, as long as the
1410 abbreviation is unambiguous. The following are the keys currently
1418 abbreviation is unambiguous. The following are the keys currently
1411 defined:
1419 defined:
1412
1420
1413 Valid Arg Meaning
1421 Valid Arg Meaning
1414 "calls" call count
1422 "calls" call count
1415 "cumulative" cumulative time
1423 "cumulative" cumulative time
1416 "file" file name
1424 "file" file name
1417 "module" file name
1425 "module" file name
1418 "pcalls" primitive call count
1426 "pcalls" primitive call count
1419 "line" line number
1427 "line" line number
1420 "name" function name
1428 "name" function name
1421 "nfl" name/file/line
1429 "nfl" name/file/line
1422 "stdname" standard name
1430 "stdname" standard name
1423 "time" internal time
1431 "time" internal time
1424
1432
1425 Note that all sorts on statistics are in descending order (placing
1433 Note that all sorts on statistics are in descending order (placing
1426 most time consuming items first), where as name, file, and line number
1434 most time consuming items first), where as name, file, and line number
1427 searches are in ascending order (i.e., alphabetical). The subtle
1435 searches are in ascending order (i.e., alphabetical). The subtle
1428 distinction between "nfl" and "stdname" is that the standard name is a
1436 distinction between "nfl" and "stdname" is that the standard name is a
1429 sort of the name as printed, which means that the embedded line
1437 sort of the name as printed, which means that the embedded line
1430 numbers get compared in an odd way. For example, lines 3, 20, and 40
1438 numbers get compared in an odd way. For example, lines 3, 20, and 40
1431 would (if the file names were the same) appear in the string order
1439 would (if the file names were the same) appear in the string order
1432 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1440 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1433 line numbers. In fact, sort_stats("nfl") is the same as
1441 line numbers. In fact, sort_stats("nfl") is the same as
1434 sort_stats("name", "file", "line").
1442 sort_stats("name", "file", "line").
1435
1443
1436 -T <filename>: save profile results as shown on screen to a text
1444 -T <filename>: save profile results as shown on screen to a text
1437 file. The profile is still shown on screen.
1445 file. The profile is still shown on screen.
1438
1446
1439 -D <filename>: save (via dump_stats) profile statistics to given
1447 -D <filename>: save (via dump_stats) profile statistics to given
1440 filename. This data is in a format understod by the pstats module, and
1448 filename. This data is in a format understod by the pstats module, and
1441 is generated by a call to the dump_stats() method of profile
1449 is generated by a call to the dump_stats() method of profile
1442 objects. The profile is still shown on screen.
1450 objects. The profile is still shown on screen.
1443
1451
1444 If you want to run complete programs under the profiler's control, use
1452 If you want to run complete programs under the profiler's control, use
1445 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1453 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1446 contains profiler specific options as described here.
1454 contains profiler specific options as described here.
1447
1455
1448 You can read the complete documentation for the profile module with::
1456 You can read the complete documentation for the profile module with::
1449
1457
1450 In [1]: import profile; profile.help()
1458 In [1]: import profile; profile.help()
1451 """
1459 """
1452
1460
1453 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1461 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1454 # protect user quote marks
1462 # protect user quote marks
1455 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1463 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1456
1464
1457 if user_mode: # regular user call
1465 if user_mode: # regular user call
1458 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1466 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1459 list_all=1)
1467 list_all=1)
1460 namespace = self.shell.user_ns
1468 namespace = self.shell.user_ns
1461 else: # called to run a program by %run -p
1469 else: # called to run a program by %run -p
1462 try:
1470 try:
1463 filename = get_py_filename(arg_lst[0])
1471 filename = get_py_filename(arg_lst[0])
1464 except IOError,msg:
1472 except IOError,msg:
1465 error(msg)
1473 error(msg)
1466 return
1474 return
1467
1475
1468 arg_str = 'execfile(filename,prog_ns)'
1476 arg_str = 'execfile(filename,prog_ns)'
1469 namespace = locals()
1477 namespace = locals()
1470
1478
1471 opts.merge(opts_def)
1479 opts.merge(opts_def)
1472
1480
1473 prof = profile.Profile()
1481 prof = profile.Profile()
1474 try:
1482 try:
1475 prof = prof.runctx(arg_str,namespace,namespace)
1483 prof = prof.runctx(arg_str,namespace,namespace)
1476 sys_exit = ''
1484 sys_exit = ''
1477 except SystemExit:
1485 except SystemExit:
1478 sys_exit = """*** SystemExit exception caught in code being profiled."""
1486 sys_exit = """*** SystemExit exception caught in code being profiled."""
1479
1487
1480 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1488 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1481
1489
1482 lims = opts.l
1490 lims = opts.l
1483 if lims:
1491 if lims:
1484 lims = [] # rebuild lims with ints/floats/strings
1492 lims = [] # rebuild lims with ints/floats/strings
1485 for lim in opts.l:
1493 for lim in opts.l:
1486 try:
1494 try:
1487 lims.append(int(lim))
1495 lims.append(int(lim))
1488 except ValueError:
1496 except ValueError:
1489 try:
1497 try:
1490 lims.append(float(lim))
1498 lims.append(float(lim))
1491 except ValueError:
1499 except ValueError:
1492 lims.append(lim)
1500 lims.append(lim)
1493
1501
1494 # Trap output.
1502 # Trap output.
1495 stdout_trap = StringIO()
1503 stdout_trap = StringIO()
1496
1504
1497 if hasattr(stats,'stream'):
1505 if hasattr(stats,'stream'):
1498 # In newer versions of python, the stats object has a 'stream'
1506 # In newer versions of python, the stats object has a 'stream'
1499 # attribute to write into.
1507 # attribute to write into.
1500 stats.stream = stdout_trap
1508 stats.stream = stdout_trap
1501 stats.print_stats(*lims)
1509 stats.print_stats(*lims)
1502 else:
1510 else:
1503 # For older versions, we manually redirect stdout during printing
1511 # For older versions, we manually redirect stdout during printing
1504 sys_stdout = sys.stdout
1512 sys_stdout = sys.stdout
1505 try:
1513 try:
1506 sys.stdout = stdout_trap
1514 sys.stdout = stdout_trap
1507 stats.print_stats(*lims)
1515 stats.print_stats(*lims)
1508 finally:
1516 finally:
1509 sys.stdout = sys_stdout
1517 sys.stdout = sys_stdout
1510
1518
1511 output = stdout_trap.getvalue()
1519 output = stdout_trap.getvalue()
1512 output = output.rstrip()
1520 output = output.rstrip()
1513
1521
1514 page(output,screen_lines=self.shell.usable_screen_length)
1522 page(output,screen_lines=self.shell.usable_screen_length)
1515 print sys_exit,
1523 print sys_exit,
1516
1524
1517 dump_file = opts.D[0]
1525 dump_file = opts.D[0]
1518 text_file = opts.T[0]
1526 text_file = opts.T[0]
1519 if dump_file:
1527 if dump_file:
1520 prof.dump_stats(dump_file)
1528 prof.dump_stats(dump_file)
1521 print '\n*** Profile stats marshalled to file',\
1529 print '\n*** Profile stats marshalled to file',\
1522 `dump_file`+'.',sys_exit
1530 `dump_file`+'.',sys_exit
1523 if text_file:
1531 if text_file:
1524 pfile = file(text_file,'w')
1532 pfile = file(text_file,'w')
1525 pfile.write(output)
1533 pfile.write(output)
1526 pfile.close()
1534 pfile.close()
1527 print '\n*** Profile printout saved to text file',\
1535 print '\n*** Profile printout saved to text file',\
1528 `text_file`+'.',sys_exit
1536 `text_file`+'.',sys_exit
1529
1537
1530 if opts.has_key('r'):
1538 if opts.has_key('r'):
1531 return stats
1539 return stats
1532 else:
1540 else:
1533 return None
1541 return None
1534
1542
1535 @testdec.skip_doctest
1543 @testdec.skip_doctest
1536 def magic_run(self, parameter_s ='',runner=None,
1544 def magic_run(self, parameter_s ='',runner=None,
1537 file_finder=get_py_filename):
1545 file_finder=get_py_filename):
1538 """Run the named file inside IPython as a program.
1546 """Run the named file inside IPython as a program.
1539
1547
1540 Usage:\\
1548 Usage:\\
1541 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1549 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1542
1550
1543 Parameters after the filename are passed as command-line arguments to
1551 Parameters after the filename are passed as command-line arguments to
1544 the program (put in sys.argv). Then, control returns to IPython's
1552 the program (put in sys.argv). Then, control returns to IPython's
1545 prompt.
1553 prompt.
1546
1554
1547 This is similar to running at a system prompt:\\
1555 This is similar to running at a system prompt:\\
1548 $ python file args\\
1556 $ python file args\\
1549 but with the advantage of giving you IPython's tracebacks, and of
1557 but with the advantage of giving you IPython's tracebacks, and of
1550 loading all variables into your interactive namespace for further use
1558 loading all variables into your interactive namespace for further use
1551 (unless -p is used, see below).
1559 (unless -p is used, see below).
1552
1560
1553 The file is executed in a namespace initially consisting only of
1561 The file is executed in a namespace initially consisting only of
1554 __name__=='__main__' and sys.argv constructed as indicated. It thus
1562 __name__=='__main__' and sys.argv constructed as indicated. It thus
1555 sees its environment as if it were being run as a stand-alone program
1563 sees its environment as if it were being run as a stand-alone program
1556 (except for sharing global objects such as previously imported
1564 (except for sharing global objects such as previously imported
1557 modules). But after execution, the IPython interactive namespace gets
1565 modules). But after execution, the IPython interactive namespace gets
1558 updated with all variables defined in the program (except for __name__
1566 updated with all variables defined in the program (except for __name__
1559 and sys.argv). This allows for very convenient loading of code for
1567 and sys.argv). This allows for very convenient loading of code for
1560 interactive work, while giving each program a 'clean sheet' to run in.
1568 interactive work, while giving each program a 'clean sheet' to run in.
1561
1569
1562 Options:
1570 Options:
1563
1571
1564 -n: __name__ is NOT set to '__main__', but to the running file's name
1572 -n: __name__ is NOT set to '__main__', but to the running file's name
1565 without extension (as python does under import). This allows running
1573 without extension (as python does under import). This allows running
1566 scripts and reloading the definitions in them without calling code
1574 scripts and reloading the definitions in them without calling code
1567 protected by an ' if __name__ == "__main__" ' clause.
1575 protected by an ' if __name__ == "__main__" ' clause.
1568
1576
1569 -i: run the file in IPython's namespace instead of an empty one. This
1577 -i: run the file in IPython's namespace instead of an empty one. This
1570 is useful if you are experimenting with code written in a text editor
1578 is useful if you are experimenting with code written in a text editor
1571 which depends on variables defined interactively.
1579 which depends on variables defined interactively.
1572
1580
1573 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1581 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1574 being run. This is particularly useful if IPython is being used to
1582 being run. This is particularly useful if IPython is being used to
1575 run unittests, which always exit with a sys.exit() call. In such
1583 run unittests, which always exit with a sys.exit() call. In such
1576 cases you are interested in the output of the test results, not in
1584 cases you are interested in the output of the test results, not in
1577 seeing a traceback of the unittest module.
1585 seeing a traceback of the unittest module.
1578
1586
1579 -t: print timing information at the end of the run. IPython will give
1587 -t: print timing information at the end of the run. IPython will give
1580 you an estimated CPU time consumption for your script, which under
1588 you an estimated CPU time consumption for your script, which under
1581 Unix uses the resource module to avoid the wraparound problems of
1589 Unix uses the resource module to avoid the wraparound problems of
1582 time.clock(). Under Unix, an estimate of time spent on system tasks
1590 time.clock(). Under Unix, an estimate of time spent on system tasks
1583 is also given (for Windows platforms this is reported as 0.0).
1591 is also given (for Windows platforms this is reported as 0.0).
1584
1592
1585 If -t is given, an additional -N<N> option can be given, where <N>
1593 If -t is given, an additional -N<N> option can be given, where <N>
1586 must be an integer indicating how many times you want the script to
1594 must be an integer indicating how many times you want the script to
1587 run. The final timing report will include total and per run results.
1595 run. The final timing report will include total and per run results.
1588
1596
1589 For example (testing the script uniq_stable.py):
1597 For example (testing the script uniq_stable.py):
1590
1598
1591 In [1]: run -t uniq_stable
1599 In [1]: run -t uniq_stable
1592
1600
1593 IPython CPU timings (estimated):\\
1601 IPython CPU timings (estimated):\\
1594 User : 0.19597 s.\\
1602 User : 0.19597 s.\\
1595 System: 0.0 s.\\
1603 System: 0.0 s.\\
1596
1604
1597 In [2]: run -t -N5 uniq_stable
1605 In [2]: run -t -N5 uniq_stable
1598
1606
1599 IPython CPU timings (estimated):\\
1607 IPython CPU timings (estimated):\\
1600 Total runs performed: 5\\
1608 Total runs performed: 5\\
1601 Times : Total Per run\\
1609 Times : Total Per run\\
1602 User : 0.910862 s, 0.1821724 s.\\
1610 User : 0.910862 s, 0.1821724 s.\\
1603 System: 0.0 s, 0.0 s.
1611 System: 0.0 s, 0.0 s.
1604
1612
1605 -d: run your program under the control of pdb, the Python debugger.
1613 -d: run your program under the control of pdb, the Python debugger.
1606 This allows you to execute your program step by step, watch variables,
1614 This allows you to execute your program step by step, watch variables,
1607 etc. Internally, what IPython does is similar to calling:
1615 etc. Internally, what IPython does is similar to calling:
1608
1616
1609 pdb.run('execfile("YOURFILENAME")')
1617 pdb.run('execfile("YOURFILENAME")')
1610
1618
1611 with a breakpoint set on line 1 of your file. You can change the line
1619 with a breakpoint set on line 1 of your file. You can change the line
1612 number for this automatic breakpoint to be <N> by using the -bN option
1620 number for this automatic breakpoint to be <N> by using the -bN option
1613 (where N must be an integer). For example:
1621 (where N must be an integer). For example:
1614
1622
1615 %run -d -b40 myscript
1623 %run -d -b40 myscript
1616
1624
1617 will set the first breakpoint at line 40 in myscript.py. Note that
1625 will set the first breakpoint at line 40 in myscript.py. Note that
1618 the first breakpoint must be set on a line which actually does
1626 the first breakpoint must be set on a line which actually does
1619 something (not a comment or docstring) for it to stop execution.
1627 something (not a comment or docstring) for it to stop execution.
1620
1628
1621 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1629 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1622 first enter 'c' (without qoutes) to start execution up to the first
1630 first enter 'c' (without qoutes) to start execution up to the first
1623 breakpoint.
1631 breakpoint.
1624
1632
1625 Entering 'help' gives information about the use of the debugger. You
1633 Entering 'help' gives information about the use of the debugger. You
1626 can easily see pdb's full documentation with "import pdb;pdb.help()"
1634 can easily see pdb's full documentation with "import pdb;pdb.help()"
1627 at a prompt.
1635 at a prompt.
1628
1636
1629 -p: run program under the control of the Python profiler module (which
1637 -p: run program under the control of the Python profiler module (which
1630 prints a detailed report of execution times, function calls, etc).
1638 prints a detailed report of execution times, function calls, etc).
1631
1639
1632 You can pass other options after -p which affect the behavior of the
1640 You can pass other options after -p which affect the behavior of the
1633 profiler itself. See the docs for %prun for details.
1641 profiler itself. See the docs for %prun for details.
1634
1642
1635 In this mode, the program's variables do NOT propagate back to the
1643 In this mode, the program's variables do NOT propagate back to the
1636 IPython interactive namespace (because they remain in the namespace
1644 IPython interactive namespace (because they remain in the namespace
1637 where the profiler executes them).
1645 where the profiler executes them).
1638
1646
1639 Internally this triggers a call to %prun, see its documentation for
1647 Internally this triggers a call to %prun, see its documentation for
1640 details on the options available specifically for profiling.
1648 details on the options available specifically for profiling.
1641
1649
1642 There is one special usage for which the text above doesn't apply:
1650 There is one special usage for which the text above doesn't apply:
1643 if the filename ends with .ipy, the file is run as ipython script,
1651 if the filename ends with .ipy, the file is run as ipython script,
1644 just as if the commands were written on IPython prompt.
1652 just as if the commands were written on IPython prompt.
1645 """
1653 """
1646
1654
1647 # get arguments and set sys.argv for program to be run.
1655 # get arguments and set sys.argv for program to be run.
1648 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1656 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1649 mode='list',list_all=1)
1657 mode='list',list_all=1)
1650
1658
1651 try:
1659 try:
1652 filename = file_finder(arg_lst[0])
1660 filename = file_finder(arg_lst[0])
1653 except IndexError:
1661 except IndexError:
1654 warn('you must provide at least a filename.')
1662 warn('you must provide at least a filename.')
1655 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1663 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1656 return
1664 return
1657 except IOError,msg:
1665 except IOError,msg:
1658 error(msg)
1666 error(msg)
1659 return
1667 return
1660
1668
1661 if filename.lower().endswith('.ipy'):
1669 if filename.lower().endswith('.ipy'):
1662 self.shell.safe_execfile_ipy(filename)
1670 self.shell.safe_execfile_ipy(filename)
1663 return
1671 return
1664
1672
1665 # Control the response to exit() calls made by the script being run
1673 # Control the response to exit() calls made by the script being run
1666 exit_ignore = opts.has_key('e')
1674 exit_ignore = opts.has_key('e')
1667
1675
1668 # Make sure that the running script gets a proper sys.argv as if it
1676 # Make sure that the running script gets a proper sys.argv as if it
1669 # were run from a system shell.
1677 # were run from a system shell.
1670 save_argv = sys.argv # save it for later restoring
1678 save_argv = sys.argv # save it for later restoring
1671 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1679 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1672
1680
1673 if opts.has_key('i'):
1681 if opts.has_key('i'):
1674 # Run in user's interactive namespace
1682 # Run in user's interactive namespace
1675 prog_ns = self.shell.user_ns
1683 prog_ns = self.shell.user_ns
1676 __name__save = self.shell.user_ns['__name__']
1684 __name__save = self.shell.user_ns['__name__']
1677 prog_ns['__name__'] = '__main__'
1685 prog_ns['__name__'] = '__main__'
1678 main_mod = self.shell.new_main_mod(prog_ns)
1686 main_mod = self.shell.new_main_mod(prog_ns)
1679 else:
1687 else:
1680 # Run in a fresh, empty namespace
1688 # Run in a fresh, empty namespace
1681 if opts.has_key('n'):
1689 if opts.has_key('n'):
1682 name = os.path.splitext(os.path.basename(filename))[0]
1690 name = os.path.splitext(os.path.basename(filename))[0]
1683 else:
1691 else:
1684 name = '__main__'
1692 name = '__main__'
1685
1693
1686 main_mod = self.shell.new_main_mod()
1694 main_mod = self.shell.new_main_mod()
1687 prog_ns = main_mod.__dict__
1695 prog_ns = main_mod.__dict__
1688 prog_ns['__name__'] = name
1696 prog_ns['__name__'] = name
1689
1697
1690 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1698 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1691 # set the __file__ global in the script's namespace
1699 # set the __file__ global in the script's namespace
1692 prog_ns['__file__'] = filename
1700 prog_ns['__file__'] = filename
1693
1701
1694 # pickle fix. See iplib for an explanation. But we need to make sure
1702 # pickle fix. See iplib for an explanation. But we need to make sure
1695 # that, if we overwrite __main__, we replace it at the end
1703 # that, if we overwrite __main__, we replace it at the end
1696 main_mod_name = prog_ns['__name__']
1704 main_mod_name = prog_ns['__name__']
1697
1705
1698 if main_mod_name == '__main__':
1706 if main_mod_name == '__main__':
1699 restore_main = sys.modules['__main__']
1707 restore_main = sys.modules['__main__']
1700 else:
1708 else:
1701 restore_main = False
1709 restore_main = False
1702
1710
1703 # This needs to be undone at the end to prevent holding references to
1711 # This needs to be undone at the end to prevent holding references to
1704 # every single object ever created.
1712 # every single object ever created.
1705 sys.modules[main_mod_name] = main_mod
1713 sys.modules[main_mod_name] = main_mod
1706
1714
1707 stats = None
1715 stats = None
1708 try:
1716 try:
1709 self.shell.savehist()
1717 self.shell.savehist()
1710
1718
1711 if opts.has_key('p'):
1719 if opts.has_key('p'):
1712 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1720 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1713 else:
1721 else:
1714 if opts.has_key('d'):
1722 if opts.has_key('d'):
1715 deb = debugger.Pdb(self.shell.colors)
1723 deb = debugger.Pdb(self.shell.colors)
1716 # reset Breakpoint state, which is moronically kept
1724 # reset Breakpoint state, which is moronically kept
1717 # in a class
1725 # in a class
1718 bdb.Breakpoint.next = 1
1726 bdb.Breakpoint.next = 1
1719 bdb.Breakpoint.bplist = {}
1727 bdb.Breakpoint.bplist = {}
1720 bdb.Breakpoint.bpbynumber = [None]
1728 bdb.Breakpoint.bpbynumber = [None]
1721 # Set an initial breakpoint to stop execution
1729 # Set an initial breakpoint to stop execution
1722 maxtries = 10
1730 maxtries = 10
1723 bp = int(opts.get('b',[1])[0])
1731 bp = int(opts.get('b',[1])[0])
1724 checkline = deb.checkline(filename,bp)
1732 checkline = deb.checkline(filename,bp)
1725 if not checkline:
1733 if not checkline:
1726 for bp in range(bp+1,bp+maxtries+1):
1734 for bp in range(bp+1,bp+maxtries+1):
1727 if deb.checkline(filename,bp):
1735 if deb.checkline(filename,bp):
1728 break
1736 break
1729 else:
1737 else:
1730 msg = ("\nI failed to find a valid line to set "
1738 msg = ("\nI failed to find a valid line to set "
1731 "a breakpoint\n"
1739 "a breakpoint\n"
1732 "after trying up to line: %s.\n"
1740 "after trying up to line: %s.\n"
1733 "Please set a valid breakpoint manually "
1741 "Please set a valid breakpoint manually "
1734 "with the -b option." % bp)
1742 "with the -b option." % bp)
1735 error(msg)
1743 error(msg)
1736 return
1744 return
1737 # if we find a good linenumber, set the breakpoint
1745 # if we find a good linenumber, set the breakpoint
1738 deb.do_break('%s:%s' % (filename,bp))
1746 deb.do_break('%s:%s' % (filename,bp))
1739 # Start file run
1747 # Start file run
1740 print "NOTE: Enter 'c' at the",
1748 print "NOTE: Enter 'c' at the",
1741 print "%s prompt to start your script." % deb.prompt
1749 print "%s prompt to start your script." % deb.prompt
1742 try:
1750 try:
1743 deb.run('execfile("%s")' % filename,prog_ns)
1751 deb.run('execfile("%s")' % filename,prog_ns)
1744
1752
1745 except:
1753 except:
1746 etype, value, tb = sys.exc_info()
1754 etype, value, tb = sys.exc_info()
1747 # Skip three frames in the traceback: the %run one,
1755 # Skip three frames in the traceback: the %run one,
1748 # one inside bdb.py, and the command-line typed by the
1756 # one inside bdb.py, and the command-line typed by the
1749 # user (run by exec in pdb itself).
1757 # user (run by exec in pdb itself).
1750 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1758 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1751 else:
1759 else:
1752 if runner is None:
1760 if runner is None:
1753 runner = self.shell.safe_execfile
1761 runner = self.shell.safe_execfile
1754 if opts.has_key('t'):
1762 if opts.has_key('t'):
1755 # timed execution
1763 # timed execution
1756 try:
1764 try:
1757 nruns = int(opts['N'][0])
1765 nruns = int(opts['N'][0])
1758 if nruns < 1:
1766 if nruns < 1:
1759 error('Number of runs must be >=1')
1767 error('Number of runs must be >=1')
1760 return
1768 return
1761 except (KeyError):
1769 except (KeyError):
1762 nruns = 1
1770 nruns = 1
1763 if nruns == 1:
1771 if nruns == 1:
1764 t0 = clock2()
1772 t0 = clock2()
1765 runner(filename,prog_ns,prog_ns,
1773 runner(filename,prog_ns,prog_ns,
1766 exit_ignore=exit_ignore)
1774 exit_ignore=exit_ignore)
1767 t1 = clock2()
1775 t1 = clock2()
1768 t_usr = t1[0]-t0[0]
1776 t_usr = t1[0]-t0[0]
1769 t_sys = t1[1]-t0[1]
1777 t_sys = t1[1]-t0[1]
1770 print "\nIPython CPU timings (estimated):"
1778 print "\nIPython CPU timings (estimated):"
1771 print " User : %10s s." % t_usr
1779 print " User : %10s s." % t_usr
1772 print " System: %10s s." % t_sys
1780 print " System: %10s s." % t_sys
1773 else:
1781 else:
1774 runs = range(nruns)
1782 runs = range(nruns)
1775 t0 = clock2()
1783 t0 = clock2()
1776 for nr in runs:
1784 for nr in runs:
1777 runner(filename,prog_ns,prog_ns,
1785 runner(filename,prog_ns,prog_ns,
1778 exit_ignore=exit_ignore)
1786 exit_ignore=exit_ignore)
1779 t1 = clock2()
1787 t1 = clock2()
1780 t_usr = t1[0]-t0[0]
1788 t_usr = t1[0]-t0[0]
1781 t_sys = t1[1]-t0[1]
1789 t_sys = t1[1]-t0[1]
1782 print "\nIPython CPU timings (estimated):"
1790 print "\nIPython CPU timings (estimated):"
1783 print "Total runs performed:",nruns
1791 print "Total runs performed:",nruns
1784 print " Times : %10s %10s" % ('Total','Per run')
1792 print " Times : %10s %10s" % ('Total','Per run')
1785 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1793 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1786 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1794 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1787
1795
1788 else:
1796 else:
1789 # regular execution
1797 # regular execution
1790 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1798 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1791
1799
1792 if opts.has_key('i'):
1800 if opts.has_key('i'):
1793 self.shell.user_ns['__name__'] = __name__save
1801 self.shell.user_ns['__name__'] = __name__save
1794 else:
1802 else:
1795 # The shell MUST hold a reference to prog_ns so after %run
1803 # The shell MUST hold a reference to prog_ns so after %run
1796 # exits, the python deletion mechanism doesn't zero it out
1804 # exits, the python deletion mechanism doesn't zero it out
1797 # (leaving dangling references).
1805 # (leaving dangling references).
1798 self.shell.cache_main_mod(prog_ns,filename)
1806 self.shell.cache_main_mod(prog_ns,filename)
1799 # update IPython interactive namespace
1807 # update IPython interactive namespace
1800
1808
1801 # Some forms of read errors on the file may mean the
1809 # Some forms of read errors on the file may mean the
1802 # __name__ key was never set; using pop we don't have to
1810 # __name__ key was never set; using pop we don't have to
1803 # worry about a possible KeyError.
1811 # worry about a possible KeyError.
1804 prog_ns.pop('__name__', None)
1812 prog_ns.pop('__name__', None)
1805
1813
1806 self.shell.user_ns.update(prog_ns)
1814 self.shell.user_ns.update(prog_ns)
1807 finally:
1815 finally:
1808 # It's a bit of a mystery why, but __builtins__ can change from
1816 # It's a bit of a mystery why, but __builtins__ can change from
1809 # being a module to becoming a dict missing some key data after
1817 # being a module to becoming a dict missing some key data after
1810 # %run. As best I can see, this is NOT something IPython is doing
1818 # %run. As best I can see, this is NOT something IPython is doing
1811 # at all, and similar problems have been reported before:
1819 # at all, and similar problems have been reported before:
1812 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1820 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1813 # Since this seems to be done by the interpreter itself, the best
1821 # Since this seems to be done by the interpreter itself, the best
1814 # we can do is to at least restore __builtins__ for the user on
1822 # we can do is to at least restore __builtins__ for the user on
1815 # exit.
1823 # exit.
1816 self.shell.user_ns['__builtins__'] = __builtin__
1824 self.shell.user_ns['__builtins__'] = __builtin__
1817
1825
1818 # Ensure key global structures are restored
1826 # Ensure key global structures are restored
1819 sys.argv = save_argv
1827 sys.argv = save_argv
1820 if restore_main:
1828 if restore_main:
1821 sys.modules['__main__'] = restore_main
1829 sys.modules['__main__'] = restore_main
1822 else:
1830 else:
1823 # Remove from sys.modules the reference to main_mod we'd
1831 # Remove from sys.modules the reference to main_mod we'd
1824 # added. Otherwise it will trap references to objects
1832 # added. Otherwise it will trap references to objects
1825 # contained therein.
1833 # contained therein.
1826 del sys.modules[main_mod_name]
1834 del sys.modules[main_mod_name]
1827
1835
1828 self.shell.reloadhist()
1836 self.shell.reloadhist()
1829
1837
1830 return stats
1838 return stats
1831
1839
1832 @testdec.skip_doctest
1840 @testdec.skip_doctest
1833 def magic_timeit(self, parameter_s =''):
1841 def magic_timeit(self, parameter_s =''):
1834 """Time execution of a Python statement or expression
1842 """Time execution of a Python statement or expression
1835
1843
1836 Usage:\\
1844 Usage:\\
1837 %timeit [-n<N> -r<R> [-t|-c]] statement
1845 %timeit [-n<N> -r<R> [-t|-c]] statement
1838
1846
1839 Time execution of a Python statement or expression using the timeit
1847 Time execution of a Python statement or expression using the timeit
1840 module.
1848 module.
1841
1849
1842 Options:
1850 Options:
1843 -n<N>: execute the given statement <N> times in a loop. If this value
1851 -n<N>: execute the given statement <N> times in a loop. If this value
1844 is not given, a fitting value is chosen.
1852 is not given, a fitting value is chosen.
1845
1853
1846 -r<R>: repeat the loop iteration <R> times and take the best result.
1854 -r<R>: repeat the loop iteration <R> times and take the best result.
1847 Default: 3
1855 Default: 3
1848
1856
1849 -t: use time.time to measure the time, which is the default on Unix.
1857 -t: use time.time to measure the time, which is the default on Unix.
1850 This function measures wall time.
1858 This function measures wall time.
1851
1859
1852 -c: use time.clock to measure the time, which is the default on
1860 -c: use time.clock to measure the time, which is the default on
1853 Windows and measures wall time. On Unix, resource.getrusage is used
1861 Windows and measures wall time. On Unix, resource.getrusage is used
1854 instead and returns the CPU user time.
1862 instead and returns the CPU user time.
1855
1863
1856 -p<P>: use a precision of <P> digits to display the timing result.
1864 -p<P>: use a precision of <P> digits to display the timing result.
1857 Default: 3
1865 Default: 3
1858
1866
1859
1867
1860 Examples:
1868 Examples:
1861
1869
1862 In [1]: %timeit pass
1870 In [1]: %timeit pass
1863 10000000 loops, best of 3: 53.3 ns per loop
1871 10000000 loops, best of 3: 53.3 ns per loop
1864
1872
1865 In [2]: u = None
1873 In [2]: u = None
1866
1874
1867 In [3]: %timeit u is None
1875 In [3]: %timeit u is None
1868 10000000 loops, best of 3: 184 ns per loop
1876 10000000 loops, best of 3: 184 ns per loop
1869
1877
1870 In [4]: %timeit -r 4 u == None
1878 In [4]: %timeit -r 4 u == None
1871 1000000 loops, best of 4: 242 ns per loop
1879 1000000 loops, best of 4: 242 ns per loop
1872
1880
1873 In [5]: import time
1881 In [5]: import time
1874
1882
1875 In [6]: %timeit -n1 time.sleep(2)
1883 In [6]: %timeit -n1 time.sleep(2)
1876 1 loops, best of 3: 2 s per loop
1884 1 loops, best of 3: 2 s per loop
1877
1885
1878
1886
1879 The times reported by %timeit will be slightly higher than those
1887 The times reported by %timeit will be slightly higher than those
1880 reported by the timeit.py script when variables are accessed. This is
1888 reported by the timeit.py script when variables are accessed. This is
1881 due to the fact that %timeit executes the statement in the namespace
1889 due to the fact that %timeit executes the statement in the namespace
1882 of the shell, compared with timeit.py, which uses a single setup
1890 of the shell, compared with timeit.py, which uses a single setup
1883 statement to import function or create variables. Generally, the bias
1891 statement to import function or create variables. Generally, the bias
1884 does not matter as long as results from timeit.py are not mixed with
1892 does not matter as long as results from timeit.py are not mixed with
1885 those from %timeit."""
1893 those from %timeit."""
1886
1894
1887 import timeit
1895 import timeit
1888 import math
1896 import math
1889
1897
1890 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1898 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1891 # certain terminals. Until we figure out a robust way of
1899 # certain terminals. Until we figure out a robust way of
1892 # auto-detecting if the terminal can deal with it, use plain 'us' for
1900 # auto-detecting if the terminal can deal with it, use plain 'us' for
1893 # microseconds. I am really NOT happy about disabling the proper
1901 # microseconds. I am really NOT happy about disabling the proper
1894 # 'micro' prefix, but crashing is worse... If anyone knows what the
1902 # 'micro' prefix, but crashing is worse... If anyone knows what the
1895 # right solution for this is, I'm all ears...
1903 # right solution for this is, I'm all ears...
1896 #
1904 #
1897 # Note: using
1905 # Note: using
1898 #
1906 #
1899 # s = u'\xb5'
1907 # s = u'\xb5'
1900 # s.encode(sys.getdefaultencoding())
1908 # s.encode(sys.getdefaultencoding())
1901 #
1909 #
1902 # is not sufficient, as I've seen terminals where that fails but
1910 # is not sufficient, as I've seen terminals where that fails but
1903 # print s
1911 # print s
1904 #
1912 #
1905 # succeeds
1913 # succeeds
1906 #
1914 #
1907 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1915 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1908
1916
1909 #units = [u"s", u"ms",u'\xb5',"ns"]
1917 #units = [u"s", u"ms",u'\xb5',"ns"]
1910 units = [u"s", u"ms",u'us',"ns"]
1918 units = [u"s", u"ms",u'us',"ns"]
1911
1919
1912 scaling = [1, 1e3, 1e6, 1e9]
1920 scaling = [1, 1e3, 1e6, 1e9]
1913
1921
1914 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1922 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1915 posix=False)
1923 posix=False)
1916 if stmt == "":
1924 if stmt == "":
1917 return
1925 return
1918 timefunc = timeit.default_timer
1926 timefunc = timeit.default_timer
1919 number = int(getattr(opts, "n", 0))
1927 number = int(getattr(opts, "n", 0))
1920 repeat = int(getattr(opts, "r", timeit.default_repeat))
1928 repeat = int(getattr(opts, "r", timeit.default_repeat))
1921 precision = int(getattr(opts, "p", 3))
1929 precision = int(getattr(opts, "p", 3))
1922 if hasattr(opts, "t"):
1930 if hasattr(opts, "t"):
1923 timefunc = time.time
1931 timefunc = time.time
1924 if hasattr(opts, "c"):
1932 if hasattr(opts, "c"):
1925 timefunc = clock
1933 timefunc = clock
1926
1934
1927 timer = timeit.Timer(timer=timefunc)
1935 timer = timeit.Timer(timer=timefunc)
1928 # this code has tight coupling to the inner workings of timeit.Timer,
1936 # this code has tight coupling to the inner workings of timeit.Timer,
1929 # but is there a better way to achieve that the code stmt has access
1937 # but is there a better way to achieve that the code stmt has access
1930 # to the shell namespace?
1938 # to the shell namespace?
1931
1939
1932 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1940 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1933 'setup': "pass"}
1941 'setup': "pass"}
1934 # Track compilation time so it can be reported if too long
1942 # Track compilation time so it can be reported if too long
1935 # Minimum time above which compilation time will be reported
1943 # Minimum time above which compilation time will be reported
1936 tc_min = 0.1
1944 tc_min = 0.1
1937
1945
1938 t0 = clock()
1946 t0 = clock()
1939 code = compile(src, "<magic-timeit>", "exec")
1947 code = compile(src, "<magic-timeit>", "exec")
1940 tc = clock()-t0
1948 tc = clock()-t0
1941
1949
1942 ns = {}
1950 ns = {}
1943 exec code in self.shell.user_ns, ns
1951 exec code in self.shell.user_ns, ns
1944 timer.inner = ns["inner"]
1952 timer.inner = ns["inner"]
1945
1953
1946 if number == 0:
1954 if number == 0:
1947 # determine number so that 0.2 <= total time < 2.0
1955 # determine number so that 0.2 <= total time < 2.0
1948 number = 1
1956 number = 1
1949 for i in range(1, 10):
1957 for i in range(1, 10):
1950 if timer.timeit(number) >= 0.2:
1958 if timer.timeit(number) >= 0.2:
1951 break
1959 break
1952 number *= 10
1960 number *= 10
1953
1961
1954 best = min(timer.repeat(repeat, number)) / number
1962 best = min(timer.repeat(repeat, number)) / number
1955
1963
1956 if best > 0.0 and best < 1000.0:
1964 if best > 0.0 and best < 1000.0:
1957 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1965 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1958 elif best >= 1000.0:
1966 elif best >= 1000.0:
1959 order = 0
1967 order = 0
1960 else:
1968 else:
1961 order = 3
1969 order = 3
1962 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1970 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1963 precision,
1971 precision,
1964 best * scaling[order],
1972 best * scaling[order],
1965 units[order])
1973 units[order])
1966 if tc > tc_min:
1974 if tc > tc_min:
1967 print "Compiler time: %.2f s" % tc
1975 print "Compiler time: %.2f s" % tc
1968
1976
1969 @testdec.skip_doctest
1977 @testdec.skip_doctest
1970 def magic_time(self,parameter_s = ''):
1978 def magic_time(self,parameter_s = ''):
1971 """Time execution of a Python statement or expression.
1979 """Time execution of a Python statement or expression.
1972
1980
1973 The CPU and wall clock times are printed, and the value of the
1981 The CPU and wall clock times are printed, and the value of the
1974 expression (if any) is returned. Note that under Win32, system time
1982 expression (if any) is returned. Note that under Win32, system time
1975 is always reported as 0, since it can not be measured.
1983 is always reported as 0, since it can not be measured.
1976
1984
1977 This function provides very basic timing functionality. In Python
1985 This function provides very basic timing functionality. In Python
1978 2.3, the timeit module offers more control and sophistication, so this
1986 2.3, the timeit module offers more control and sophistication, so this
1979 could be rewritten to use it (patches welcome).
1987 could be rewritten to use it (patches welcome).
1980
1988
1981 Some examples:
1989 Some examples:
1982
1990
1983 In [1]: time 2**128
1991 In [1]: time 2**128
1984 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1992 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1985 Wall time: 0.00
1993 Wall time: 0.00
1986 Out[1]: 340282366920938463463374607431768211456L
1994 Out[1]: 340282366920938463463374607431768211456L
1987
1995
1988 In [2]: n = 1000000
1996 In [2]: n = 1000000
1989
1997
1990 In [3]: time sum(range(n))
1998 In [3]: time sum(range(n))
1991 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1999 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1992 Wall time: 1.37
2000 Wall time: 1.37
1993 Out[3]: 499999500000L
2001 Out[3]: 499999500000L
1994
2002
1995 In [4]: time print 'hello world'
2003 In [4]: time print 'hello world'
1996 hello world
2004 hello world
1997 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2005 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1998 Wall time: 0.00
2006 Wall time: 0.00
1999
2007
2000 Note that the time needed by Python to compile the given expression
2008 Note that the time needed by Python to compile the given expression
2001 will be reported if it is more than 0.1s. In this example, the
2009 will be reported if it is more than 0.1s. In this example, the
2002 actual exponentiation is done by Python at compilation time, so while
2010 actual exponentiation is done by Python at compilation time, so while
2003 the expression can take a noticeable amount of time to compute, that
2011 the expression can take a noticeable amount of time to compute, that
2004 time is purely due to the compilation:
2012 time is purely due to the compilation:
2005
2013
2006 In [5]: time 3**9999;
2014 In [5]: time 3**9999;
2007 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2015 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2008 Wall time: 0.00 s
2016 Wall time: 0.00 s
2009
2017
2010 In [6]: time 3**999999;
2018 In [6]: time 3**999999;
2011 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2019 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2012 Wall time: 0.00 s
2020 Wall time: 0.00 s
2013 Compiler : 0.78 s
2021 Compiler : 0.78 s
2014 """
2022 """
2015
2023
2016 # fail immediately if the given expression can't be compiled
2024 # fail immediately if the given expression can't be compiled
2017
2025
2018 expr = self.shell.prefilter(parameter_s,False)
2026 expr = self.shell.prefilter(parameter_s,False)
2019
2027
2020 # Minimum time above which compilation time will be reported
2028 # Minimum time above which compilation time will be reported
2021 tc_min = 0.1
2029 tc_min = 0.1
2022
2030
2023 try:
2031 try:
2024 mode = 'eval'
2032 mode = 'eval'
2025 t0 = clock()
2033 t0 = clock()
2026 code = compile(expr,'<timed eval>',mode)
2034 code = compile(expr,'<timed eval>',mode)
2027 tc = clock()-t0
2035 tc = clock()-t0
2028 except SyntaxError:
2036 except SyntaxError:
2029 mode = 'exec'
2037 mode = 'exec'
2030 t0 = clock()
2038 t0 = clock()
2031 code = compile(expr,'<timed exec>',mode)
2039 code = compile(expr,'<timed exec>',mode)
2032 tc = clock()-t0
2040 tc = clock()-t0
2033 # skew measurement as little as possible
2041 # skew measurement as little as possible
2034 glob = self.shell.user_ns
2042 glob = self.shell.user_ns
2035 clk = clock2
2043 clk = clock2
2036 wtime = time.time
2044 wtime = time.time
2037 # time execution
2045 # time execution
2038 wall_st = wtime()
2046 wall_st = wtime()
2039 if mode=='eval':
2047 if mode=='eval':
2040 st = clk()
2048 st = clk()
2041 out = eval(code,glob)
2049 out = eval(code,glob)
2042 end = clk()
2050 end = clk()
2043 else:
2051 else:
2044 st = clk()
2052 st = clk()
2045 exec code in glob
2053 exec code in glob
2046 end = clk()
2054 end = clk()
2047 out = None
2055 out = None
2048 wall_end = wtime()
2056 wall_end = wtime()
2049 # Compute actual times and report
2057 # Compute actual times and report
2050 wall_time = wall_end-wall_st
2058 wall_time = wall_end-wall_st
2051 cpu_user = end[0]-st[0]
2059 cpu_user = end[0]-st[0]
2052 cpu_sys = end[1]-st[1]
2060 cpu_sys = end[1]-st[1]
2053 cpu_tot = cpu_user+cpu_sys
2061 cpu_tot = cpu_user+cpu_sys
2054 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
2062 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
2055 (cpu_user,cpu_sys,cpu_tot)
2063 (cpu_user,cpu_sys,cpu_tot)
2056 print "Wall time: %.2f s" % wall_time
2064 print "Wall time: %.2f s" % wall_time
2057 if tc > tc_min:
2065 if tc > tc_min:
2058 print "Compiler : %.2f s" % tc
2066 print "Compiler : %.2f s" % tc
2059 return out
2067 return out
2060
2068
2061 @testdec.skip_doctest
2069 @testdec.skip_doctest
2062 def magic_macro(self,parameter_s = ''):
2070 def magic_macro(self,parameter_s = ''):
2063 """Define a set of input lines as a macro for future re-execution.
2071 """Define a set of input lines as a macro for future re-execution.
2064
2072
2065 Usage:\\
2073 Usage:\\
2066 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
2074 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
2067
2075
2068 Options:
2076 Options:
2069
2077
2070 -r: use 'raw' input. By default, the 'processed' history is used,
2078 -r: use 'raw' input. By default, the 'processed' history is used,
2071 so that magics are loaded in their transformed version to valid
2079 so that magics are loaded in their transformed version to valid
2072 Python. If this option is given, the raw input as typed as the
2080 Python. If this option is given, the raw input as typed as the
2073 command line is used instead.
2081 command line is used instead.
2074
2082
2075 This will define a global variable called `name` which is a string
2083 This will define a global variable called `name` which is a string
2076 made of joining the slices and lines you specify (n1,n2,... numbers
2084 made of joining the slices and lines you specify (n1,n2,... numbers
2077 above) from your input history into a single string. This variable
2085 above) from your input history into a single string. This variable
2078 acts like an automatic function which re-executes those lines as if
2086 acts like an automatic function which re-executes those lines as if
2079 you had typed them. You just type 'name' at the prompt and the code
2087 you had typed them. You just type 'name' at the prompt and the code
2080 executes.
2088 executes.
2081
2089
2082 The notation for indicating number ranges is: n1-n2 means 'use line
2090 The notation for indicating number ranges is: n1-n2 means 'use line
2083 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
2091 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
2084 using the lines numbered 5,6 and 7.
2092 using the lines numbered 5,6 and 7.
2085
2093
2086 Note: as a 'hidden' feature, you can also use traditional python slice
2094 Note: as a 'hidden' feature, you can also use traditional python slice
2087 notation, where N:M means numbers N through M-1.
2095 notation, where N:M means numbers N through M-1.
2088
2096
2089 For example, if your history contains (%hist prints it):
2097 For example, if your history contains (%hist prints it):
2090
2098
2091 44: x=1
2099 44: x=1
2092 45: y=3
2100 45: y=3
2093 46: z=x+y
2101 46: z=x+y
2094 47: print x
2102 47: print x
2095 48: a=5
2103 48: a=5
2096 49: print 'x',x,'y',y
2104 49: print 'x',x,'y',y
2097
2105
2098 you can create a macro with lines 44 through 47 (included) and line 49
2106 you can create a macro with lines 44 through 47 (included) and line 49
2099 called my_macro with:
2107 called my_macro with:
2100
2108
2101 In [55]: %macro my_macro 44-47 49
2109 In [55]: %macro my_macro 44-47 49
2102
2110
2103 Now, typing `my_macro` (without quotes) will re-execute all this code
2111 Now, typing `my_macro` (without quotes) will re-execute all this code
2104 in one pass.
2112 in one pass.
2105
2113
2106 You don't need to give the line-numbers in order, and any given line
2114 You don't need to give the line-numbers in order, and any given line
2107 number can appear multiple times. You can assemble macros with any
2115 number can appear multiple times. You can assemble macros with any
2108 lines from your input history in any order.
2116 lines from your input history in any order.
2109
2117
2110 The macro is a simple object which holds its value in an attribute,
2118 The macro is a simple object which holds its value in an attribute,
2111 but IPython's display system checks for macros and executes them as
2119 but IPython's display system checks for macros and executes them as
2112 code instead of printing them when you type their name.
2120 code instead of printing them when you type their name.
2113
2121
2114 You can view a macro's contents by explicitly printing it with:
2122 You can view a macro's contents by explicitly printing it with:
2115
2123
2116 'print macro_name'.
2124 'print macro_name'.
2117
2125
2118 For one-off cases which DON'T contain magic function calls in them you
2126 For one-off cases which DON'T contain magic function calls in them you
2119 can obtain similar results by explicitly executing slices from your
2127 can obtain similar results by explicitly executing slices from your
2120 input history with:
2128 input history with:
2121
2129
2122 In [60]: exec In[44:48]+In[49]"""
2130 In [60]: exec In[44:48]+In[49]"""
2123
2131
2124 opts,args = self.parse_options(parameter_s,'r',mode='list')
2132 opts,args = self.parse_options(parameter_s,'r',mode='list')
2125 if not args:
2133 if not args:
2126 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
2134 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
2127 macs.sort()
2135 macs.sort()
2128 return macs
2136 return macs
2129 if len(args) == 1:
2137 if len(args) == 1:
2130 raise UsageError(
2138 raise UsageError(
2131 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2139 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2132 name,ranges = args[0], args[1:]
2140 name,ranges = args[0], args[1:]
2133
2141
2134 #print 'rng',ranges # dbg
2142 #print 'rng',ranges # dbg
2135 lines = self.extract_input_slices(ranges,opts.has_key('r'))
2143 lines = self.extract_input_slices(ranges,opts.has_key('r'))
2136 macro = Macro(lines)
2144 macro = Macro(lines)
2137 self.shell.define_macro(name, macro)
2145 self.shell.define_macro(name, macro)
2138 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2146 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2139 print 'Macro contents:'
2147 print 'Macro contents:'
2140 print macro,
2148 print macro,
2141
2149
2142 def magic_save(self,parameter_s = ''):
2150 def magic_save(self,parameter_s = ''):
2143 """Save a set of lines to a given filename.
2151 """Save a set of lines to a given filename.
2144
2152
2145 Usage:\\
2153 Usage:\\
2146 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2154 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2147
2155
2148 Options:
2156 Options:
2149
2157
2150 -r: use 'raw' input. By default, the 'processed' history is used,
2158 -r: use 'raw' input. By default, the 'processed' history is used,
2151 so that magics are loaded in their transformed version to valid
2159 so that magics are loaded in their transformed version to valid
2152 Python. If this option is given, the raw input as typed as the
2160 Python. If this option is given, the raw input as typed as the
2153 command line is used instead.
2161 command line is used instead.
2154
2162
2155 This function uses the same syntax as %macro for line extraction, but
2163 This function uses the same syntax as %macro for line extraction, but
2156 instead of creating a macro it saves the resulting string to the
2164 instead of creating a macro it saves the resulting string to the
2157 filename you specify.
2165 filename you specify.
2158
2166
2159 It adds a '.py' extension to the file if you don't do so yourself, and
2167 It adds a '.py' extension to the file if you don't do so yourself, and
2160 it asks for confirmation before overwriting existing files."""
2168 it asks for confirmation before overwriting existing files."""
2161
2169
2162 opts,args = self.parse_options(parameter_s,'r',mode='list')
2170 opts,args = self.parse_options(parameter_s,'r',mode='list')
2163 fname,ranges = args[0], args[1:]
2171 fname,ranges = args[0], args[1:]
2164 if not fname.endswith('.py'):
2172 if not fname.endswith('.py'):
2165 fname += '.py'
2173 fname += '.py'
2166 if os.path.isfile(fname):
2174 if os.path.isfile(fname):
2167 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2175 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2168 if ans.lower() not in ['y','yes']:
2176 if ans.lower() not in ['y','yes']:
2169 print 'Operation cancelled.'
2177 print 'Operation cancelled.'
2170 return
2178 return
2171 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2179 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2172 f = file(fname,'w')
2180 f = file(fname,'w')
2173 f.write(cmds)
2181 f.write(cmds)
2174 f.close()
2182 f.close()
2175 print 'The following commands were written to file `%s`:' % fname
2183 print 'The following commands were written to file `%s`:' % fname
2176 print cmds
2184 print cmds
2177
2185
2178 def _edit_macro(self,mname,macro):
2186 def _edit_macro(self,mname,macro):
2179 """open an editor with the macro data in a file"""
2187 """open an editor with the macro data in a file"""
2180 filename = self.shell.mktempfile(macro.value)
2188 filename = self.shell.mktempfile(macro.value)
2181 self.shell.hooks.editor(filename)
2189 self.shell.hooks.editor(filename)
2182
2190
2183 # and make a new macro object, to replace the old one
2191 # and make a new macro object, to replace the old one
2184 mfile = open(filename)
2192 mfile = open(filename)
2185 mvalue = mfile.read()
2193 mvalue = mfile.read()
2186 mfile.close()
2194 mfile.close()
2187 self.shell.user_ns[mname] = Macro(mvalue)
2195 self.shell.user_ns[mname] = Macro(mvalue)
2188
2196
2189 def magic_ed(self,parameter_s=''):
2197 def magic_ed(self,parameter_s=''):
2190 """Alias to %edit."""
2198 """Alias to %edit."""
2191 return self.magic_edit(parameter_s)
2199 return self.magic_edit(parameter_s)
2192
2200
2193 @testdec.skip_doctest
2201 @testdec.skip_doctest
2194 def magic_edit(self,parameter_s='',last_call=['','']):
2202 def magic_edit(self,parameter_s='',last_call=['','']):
2195 """Bring up an editor and execute the resulting code.
2203 """Bring up an editor and execute the resulting code.
2196
2204
2197 Usage:
2205 Usage:
2198 %edit [options] [args]
2206 %edit [options] [args]
2199
2207
2200 %edit runs IPython's editor hook. The default version of this hook is
2208 %edit runs IPython's editor hook. The default version of this hook is
2201 set to call the __IPYTHON__.rc.editor command. This is read from your
2209 set to call the __IPYTHON__.rc.editor command. This is read from your
2202 environment variable $EDITOR. If this isn't found, it will default to
2210 environment variable $EDITOR. If this isn't found, it will default to
2203 vi under Linux/Unix and to notepad under Windows. See the end of this
2211 vi under Linux/Unix and to notepad under Windows. See the end of this
2204 docstring for how to change the editor hook.
2212 docstring for how to change the editor hook.
2205
2213
2206 You can also set the value of this editor via the command line option
2214 You can also set the value of this editor via the command line option
2207 '-editor' or in your ipythonrc file. This is useful if you wish to use
2215 '-editor' or in your ipythonrc file. This is useful if you wish to use
2208 specifically for IPython an editor different from your typical default
2216 specifically for IPython an editor different from your typical default
2209 (and for Windows users who typically don't set environment variables).
2217 (and for Windows users who typically don't set environment variables).
2210
2218
2211 This command allows you to conveniently edit multi-line code right in
2219 This command allows you to conveniently edit multi-line code right in
2212 your IPython session.
2220 your IPython session.
2213
2221
2214 If called without arguments, %edit opens up an empty editor with a
2222 If called without arguments, %edit opens up an empty editor with a
2215 temporary file and will execute the contents of this file when you
2223 temporary file and will execute the contents of this file when you
2216 close it (don't forget to save it!).
2224 close it (don't forget to save it!).
2217
2225
2218
2226
2219 Options:
2227 Options:
2220
2228
2221 -n <number>: open the editor at a specified line number. By default,
2229 -n <number>: open the editor at a specified line number. By default,
2222 the IPython editor hook uses the unix syntax 'editor +N filename', but
2230 the IPython editor hook uses the unix syntax 'editor +N filename', but
2223 you can configure this by providing your own modified hook if your
2231 you can configure this by providing your own modified hook if your
2224 favorite editor supports line-number specifications with a different
2232 favorite editor supports line-number specifications with a different
2225 syntax.
2233 syntax.
2226
2234
2227 -p: this will call the editor with the same data as the previous time
2235 -p: this will call the editor with the same data as the previous time
2228 it was used, regardless of how long ago (in your current session) it
2236 it was used, regardless of how long ago (in your current session) it
2229 was.
2237 was.
2230
2238
2231 -r: use 'raw' input. This option only applies to input taken from the
2239 -r: use 'raw' input. This option only applies to input taken from the
2232 user's history. By default, the 'processed' history is used, so that
2240 user's history. By default, the 'processed' history is used, so that
2233 magics are loaded in their transformed version to valid Python. If
2241 magics are loaded in their transformed version to valid Python. If
2234 this option is given, the raw input as typed as the command line is
2242 this option is given, the raw input as typed as the command line is
2235 used instead. When you exit the editor, it will be executed by
2243 used instead. When you exit the editor, it will be executed by
2236 IPython's own processor.
2244 IPython's own processor.
2237
2245
2238 -x: do not execute the edited code immediately upon exit. This is
2246 -x: do not execute the edited code immediately upon exit. This is
2239 mainly useful if you are editing programs which need to be called with
2247 mainly useful if you are editing programs which need to be called with
2240 command line arguments, which you can then do using %run.
2248 command line arguments, which you can then do using %run.
2241
2249
2242
2250
2243 Arguments:
2251 Arguments:
2244
2252
2245 If arguments are given, the following possibilites exist:
2253 If arguments are given, the following possibilites exist:
2246
2254
2247 - The arguments are numbers or pairs of colon-separated numbers (like
2255 - The arguments are numbers or pairs of colon-separated numbers (like
2248 1 4:8 9). These are interpreted as lines of previous input to be
2256 1 4:8 9). These are interpreted as lines of previous input to be
2249 loaded into the editor. The syntax is the same of the %macro command.
2257 loaded into the editor. The syntax is the same of the %macro command.
2250
2258
2251 - If the argument doesn't start with a number, it is evaluated as a
2259 - If the argument doesn't start with a number, it is evaluated as a
2252 variable and its contents loaded into the editor. You can thus edit
2260 variable and its contents loaded into the editor. You can thus edit
2253 any string which contains python code (including the result of
2261 any string which contains python code (including the result of
2254 previous edits).
2262 previous edits).
2255
2263
2256 - If the argument is the name of an object (other than a string),
2264 - If the argument is the name of an object (other than a string),
2257 IPython will try to locate the file where it was defined and open the
2265 IPython will try to locate the file where it was defined and open the
2258 editor at the point where it is defined. You can use `%edit function`
2266 editor at the point where it is defined. You can use `%edit function`
2259 to load an editor exactly at the point where 'function' is defined,
2267 to load an editor exactly at the point where 'function' is defined,
2260 edit it and have the file be executed automatically.
2268 edit it and have the file be executed automatically.
2261
2269
2262 If the object is a macro (see %macro for details), this opens up your
2270 If the object is a macro (see %macro for details), this opens up your
2263 specified editor with a temporary file containing the macro's data.
2271 specified editor with a temporary file containing the macro's data.
2264 Upon exit, the macro is reloaded with the contents of the file.
2272 Upon exit, the macro is reloaded with the contents of the file.
2265
2273
2266 Note: opening at an exact line is only supported under Unix, and some
2274 Note: opening at an exact line is only supported under Unix, and some
2267 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2275 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2268 '+NUMBER' parameter necessary for this feature. Good editors like
2276 '+NUMBER' parameter necessary for this feature. Good editors like
2269 (X)Emacs, vi, jed, pico and joe all do.
2277 (X)Emacs, vi, jed, pico and joe all do.
2270
2278
2271 - If the argument is not found as a variable, IPython will look for a
2279 - If the argument is not found as a variable, IPython will look for a
2272 file with that name (adding .py if necessary) and load it into the
2280 file with that name (adding .py if necessary) and load it into the
2273 editor. It will execute its contents with execfile() when you exit,
2281 editor. It will execute its contents with execfile() when you exit,
2274 loading any code in the file into your interactive namespace.
2282 loading any code in the file into your interactive namespace.
2275
2283
2276 After executing your code, %edit will return as output the code you
2284 After executing your code, %edit will return as output the code you
2277 typed in the editor (except when it was an existing file). This way
2285 typed in the editor (except when it was an existing file). This way
2278 you can reload the code in further invocations of %edit as a variable,
2286 you can reload the code in further invocations of %edit as a variable,
2279 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2287 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2280 the output.
2288 the output.
2281
2289
2282 Note that %edit is also available through the alias %ed.
2290 Note that %edit is also available through the alias %ed.
2283
2291
2284 This is an example of creating a simple function inside the editor and
2292 This is an example of creating a simple function inside the editor and
2285 then modifying it. First, start up the editor:
2293 then modifying it. First, start up the editor:
2286
2294
2287 In [1]: ed
2295 In [1]: ed
2288 Editing... done. Executing edited code...
2296 Editing... done. Executing edited code...
2289 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2297 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2290
2298
2291 We can then call the function foo():
2299 We can then call the function foo():
2292
2300
2293 In [2]: foo()
2301 In [2]: foo()
2294 foo() was defined in an editing session
2302 foo() was defined in an editing session
2295
2303
2296 Now we edit foo. IPython automatically loads the editor with the
2304 Now we edit foo. IPython automatically loads the editor with the
2297 (temporary) file where foo() was previously defined:
2305 (temporary) file where foo() was previously defined:
2298
2306
2299 In [3]: ed foo
2307 In [3]: ed foo
2300 Editing... done. Executing edited code...
2308 Editing... done. Executing edited code...
2301
2309
2302 And if we call foo() again we get the modified version:
2310 And if we call foo() again we get the modified version:
2303
2311
2304 In [4]: foo()
2312 In [4]: foo()
2305 foo() has now been changed!
2313 foo() has now been changed!
2306
2314
2307 Here is an example of how to edit a code snippet successive
2315 Here is an example of how to edit a code snippet successive
2308 times. First we call the editor:
2316 times. First we call the editor:
2309
2317
2310 In [5]: ed
2318 In [5]: ed
2311 Editing... done. Executing edited code...
2319 Editing... done. Executing edited code...
2312 hello
2320 hello
2313 Out[5]: "print 'hello'n"
2321 Out[5]: "print 'hello'n"
2314
2322
2315 Now we call it again with the previous output (stored in _):
2323 Now we call it again with the previous output (stored in _):
2316
2324
2317 In [6]: ed _
2325 In [6]: ed _
2318 Editing... done. Executing edited code...
2326 Editing... done. Executing edited code...
2319 hello world
2327 hello world
2320 Out[6]: "print 'hello world'n"
2328 Out[6]: "print 'hello world'n"
2321
2329
2322 Now we call it with the output #8 (stored in _8, also as Out[8]):
2330 Now we call it with the output #8 (stored in _8, also as Out[8]):
2323
2331
2324 In [7]: ed _8
2332 In [7]: ed _8
2325 Editing... done. Executing edited code...
2333 Editing... done. Executing edited code...
2326 hello again
2334 hello again
2327 Out[7]: "print 'hello again'n"
2335 Out[7]: "print 'hello again'n"
2328
2336
2329
2337
2330 Changing the default editor hook:
2338 Changing the default editor hook:
2331
2339
2332 If you wish to write your own editor hook, you can put it in a
2340 If you wish to write your own editor hook, you can put it in a
2333 configuration file which you load at startup time. The default hook
2341 configuration file which you load at startup time. The default hook
2334 is defined in the IPython.core.hooks module, and you can use that as a
2342 is defined in the IPython.core.hooks module, and you can use that as a
2335 starting example for further modifications. That file also has
2343 starting example for further modifications. That file also has
2336 general instructions on how to set a new hook for use once you've
2344 general instructions on how to set a new hook for use once you've
2337 defined it."""
2345 defined it."""
2338
2346
2339 # FIXME: This function has become a convoluted mess. It needs a
2347 # FIXME: This function has become a convoluted mess. It needs a
2340 # ground-up rewrite with clean, simple logic.
2348 # ground-up rewrite with clean, simple logic.
2341
2349
2342 def make_filename(arg):
2350 def make_filename(arg):
2343 "Make a filename from the given args"
2351 "Make a filename from the given args"
2344 try:
2352 try:
2345 filename = get_py_filename(arg)
2353 filename = get_py_filename(arg)
2346 except IOError:
2354 except IOError:
2347 if args.endswith('.py'):
2355 if args.endswith('.py'):
2348 filename = arg
2356 filename = arg
2349 else:
2357 else:
2350 filename = None
2358 filename = None
2351 return filename
2359 return filename
2352
2360
2353 # custom exceptions
2361 # custom exceptions
2354 class DataIsObject(Exception): pass
2362 class DataIsObject(Exception): pass
2355
2363
2356 opts,args = self.parse_options(parameter_s,'prxn:')
2364 opts,args = self.parse_options(parameter_s,'prxn:')
2357 # Set a few locals from the options for convenience:
2365 # Set a few locals from the options for convenience:
2358 opts_p = opts.has_key('p')
2366 opts_p = opts.has_key('p')
2359 opts_r = opts.has_key('r')
2367 opts_r = opts.has_key('r')
2360
2368
2361 # Default line number value
2369 # Default line number value
2362 lineno = opts.get('n',None)
2370 lineno = opts.get('n',None)
2363
2371
2364 if opts_p:
2372 if opts_p:
2365 args = '_%s' % last_call[0]
2373 args = '_%s' % last_call[0]
2366 if not self.shell.user_ns.has_key(args):
2374 if not self.shell.user_ns.has_key(args):
2367 args = last_call[1]
2375 args = last_call[1]
2368
2376
2369 # use last_call to remember the state of the previous call, but don't
2377 # use last_call to remember the state of the previous call, but don't
2370 # let it be clobbered by successive '-p' calls.
2378 # let it be clobbered by successive '-p' calls.
2371 try:
2379 try:
2372 last_call[0] = self.shell.outputcache.prompt_count
2380 last_call[0] = self.shell.outputcache.prompt_count
2373 if not opts_p:
2381 if not opts_p:
2374 last_call[1] = parameter_s
2382 last_call[1] = parameter_s
2375 except:
2383 except:
2376 pass
2384 pass
2377
2385
2378 # by default this is done with temp files, except when the given
2386 # by default this is done with temp files, except when the given
2379 # arg is a filename
2387 # arg is a filename
2380 use_temp = 1
2388 use_temp = 1
2381
2389
2382 if re.match(r'\d',args):
2390 if re.match(r'\d',args):
2383 # Mode where user specifies ranges of lines, like in %macro.
2391 # Mode where user specifies ranges of lines, like in %macro.
2384 # This means that you can't edit files whose names begin with
2392 # This means that you can't edit files whose names begin with
2385 # numbers this way. Tough.
2393 # numbers this way. Tough.
2386 ranges = args.split()
2394 ranges = args.split()
2387 data = ''.join(self.extract_input_slices(ranges,opts_r))
2395 data = ''.join(self.extract_input_slices(ranges,opts_r))
2388 elif args.endswith('.py'):
2396 elif args.endswith('.py'):
2389 filename = make_filename(args)
2397 filename = make_filename(args)
2390 data = ''
2398 data = ''
2391 use_temp = 0
2399 use_temp = 0
2392 elif args:
2400 elif args:
2393 try:
2401 try:
2394 # Load the parameter given as a variable. If not a string,
2402 # Load the parameter given as a variable. If not a string,
2395 # process it as an object instead (below)
2403 # process it as an object instead (below)
2396
2404
2397 #print '*** args',args,'type',type(args) # dbg
2405 #print '*** args',args,'type',type(args) # dbg
2398 data = eval(args,self.shell.user_ns)
2406 data = eval(args,self.shell.user_ns)
2399 if not type(data) in StringTypes:
2407 if not type(data) in StringTypes:
2400 raise DataIsObject
2408 raise DataIsObject
2401
2409
2402 except (NameError,SyntaxError):
2410 except (NameError,SyntaxError):
2403 # given argument is not a variable, try as a filename
2411 # given argument is not a variable, try as a filename
2404 filename = make_filename(args)
2412 filename = make_filename(args)
2405 if filename is None:
2413 if filename is None:
2406 warn("Argument given (%s) can't be found as a variable "
2414 warn("Argument given (%s) can't be found as a variable "
2407 "or as a filename." % args)
2415 "or as a filename." % args)
2408 return
2416 return
2409
2417
2410 data = ''
2418 data = ''
2411 use_temp = 0
2419 use_temp = 0
2412 except DataIsObject:
2420 except DataIsObject:
2413
2421
2414 # macros have a special edit function
2422 # macros have a special edit function
2415 if isinstance(data,Macro):
2423 if isinstance(data,Macro):
2416 self._edit_macro(args,data)
2424 self._edit_macro(args,data)
2417 return
2425 return
2418
2426
2419 # For objects, try to edit the file where they are defined
2427 # For objects, try to edit the file where they are defined
2420 try:
2428 try:
2421 filename = inspect.getabsfile(data)
2429 filename = inspect.getabsfile(data)
2422 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2430 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2423 # class created by %edit? Try to find source
2431 # class created by %edit? Try to find source
2424 # by looking for method definitions instead, the
2432 # by looking for method definitions instead, the
2425 # __module__ in those classes is FakeModule.
2433 # __module__ in those classes is FakeModule.
2426 attrs = [getattr(data, aname) for aname in dir(data)]
2434 attrs = [getattr(data, aname) for aname in dir(data)]
2427 for attr in attrs:
2435 for attr in attrs:
2428 if not inspect.ismethod(attr):
2436 if not inspect.ismethod(attr):
2429 continue
2437 continue
2430 filename = inspect.getabsfile(attr)
2438 filename = inspect.getabsfile(attr)
2431 if filename and 'fakemodule' not in filename.lower():
2439 if filename and 'fakemodule' not in filename.lower():
2432 # change the attribute to be the edit target instead
2440 # change the attribute to be the edit target instead
2433 data = attr
2441 data = attr
2434 break
2442 break
2435
2443
2436 datafile = 1
2444 datafile = 1
2437 except TypeError:
2445 except TypeError:
2438 filename = make_filename(args)
2446 filename = make_filename(args)
2439 datafile = 1
2447 datafile = 1
2440 warn('Could not find file where `%s` is defined.\n'
2448 warn('Could not find file where `%s` is defined.\n'
2441 'Opening a file named `%s`' % (args,filename))
2449 'Opening a file named `%s`' % (args,filename))
2442 # Now, make sure we can actually read the source (if it was in
2450 # Now, make sure we can actually read the source (if it was in
2443 # a temp file it's gone by now).
2451 # a temp file it's gone by now).
2444 if datafile:
2452 if datafile:
2445 try:
2453 try:
2446 if lineno is None:
2454 if lineno is None:
2447 lineno = inspect.getsourcelines(data)[1]
2455 lineno = inspect.getsourcelines(data)[1]
2448 except IOError:
2456 except IOError:
2449 filename = make_filename(args)
2457 filename = make_filename(args)
2450 if filename is None:
2458 if filename is None:
2451 warn('The file `%s` where `%s` was defined cannot '
2459 warn('The file `%s` where `%s` was defined cannot '
2452 'be read.' % (filename,data))
2460 'be read.' % (filename,data))
2453 return
2461 return
2454 use_temp = 0
2462 use_temp = 0
2455 else:
2463 else:
2456 data = ''
2464 data = ''
2457
2465
2458 if use_temp:
2466 if use_temp:
2459 filename = self.shell.mktempfile(data)
2467 filename = self.shell.mktempfile(data)
2460 print 'IPython will make a temporary file named:',filename
2468 print 'IPython will make a temporary file named:',filename
2461
2469
2462 # do actual editing here
2470 # do actual editing here
2463 print 'Editing...',
2471 print 'Editing...',
2464 sys.stdout.flush()
2472 sys.stdout.flush()
2465 try:
2473 try:
2466 # Quote filenames that may have spaces in them
2474 # Quote filenames that may have spaces in them
2467 if ' ' in filename:
2475 if ' ' in filename:
2468 filename = "%s" % filename
2476 filename = "%s" % filename
2469 self.shell.hooks.editor(filename,lineno)
2477 self.shell.hooks.editor(filename,lineno)
2470 except TryNext:
2478 except TryNext:
2471 warn('Could not open editor')
2479 warn('Could not open editor')
2472 return
2480 return
2473
2481
2474 # XXX TODO: should this be generalized for all string vars?
2482 # XXX TODO: should this be generalized for all string vars?
2475 # For now, this is special-cased to blocks created by cpaste
2483 # For now, this is special-cased to blocks created by cpaste
2476 if args.strip() == 'pasted_block':
2484 if args.strip() == 'pasted_block':
2477 self.shell.user_ns['pasted_block'] = file_read(filename)
2485 self.shell.user_ns['pasted_block'] = file_read(filename)
2478
2486
2479 if opts.has_key('x'): # -x prevents actual execution
2487 if opts.has_key('x'): # -x prevents actual execution
2480 print
2488 print
2481 else:
2489 else:
2482 print 'done. Executing edited code...'
2490 print 'done. Executing edited code...'
2483 if opts_r:
2491 if opts_r:
2484 self.shell.runlines(file_read(filename))
2492 self.shell.runlines(file_read(filename))
2485 else:
2493 else:
2486 self.shell.safe_execfile(filename,self.shell.user_ns,
2494 self.shell.safe_execfile(filename,self.shell.user_ns,
2487 self.shell.user_ns)
2495 self.shell.user_ns)
2488
2496
2489
2497
2490 if use_temp:
2498 if use_temp:
2491 try:
2499 try:
2492 return open(filename).read()
2500 return open(filename).read()
2493 except IOError,msg:
2501 except IOError,msg:
2494 if msg.filename == filename:
2502 if msg.filename == filename:
2495 warn('File not found. Did you forget to save?')
2503 warn('File not found. Did you forget to save?')
2496 return
2504 return
2497 else:
2505 else:
2498 self.shell.showtraceback()
2506 self.shell.showtraceback()
2499
2507
2500 def magic_xmode(self,parameter_s = ''):
2508 def magic_xmode(self,parameter_s = ''):
2501 """Switch modes for the exception handlers.
2509 """Switch modes for the exception handlers.
2502
2510
2503 Valid modes: Plain, Context and Verbose.
2511 Valid modes: Plain, Context and Verbose.
2504
2512
2505 If called without arguments, acts as a toggle."""
2513 If called without arguments, acts as a toggle."""
2506
2514
2507 def xmode_switch_err(name):
2515 def xmode_switch_err(name):
2508 warn('Error changing %s exception modes.\n%s' %
2516 warn('Error changing %s exception modes.\n%s' %
2509 (name,sys.exc_info()[1]))
2517 (name,sys.exc_info()[1]))
2510
2518
2511 shell = self.shell
2519 shell = self.shell
2512 new_mode = parameter_s.strip().capitalize()
2520 new_mode = parameter_s.strip().capitalize()
2513 try:
2521 try:
2514 shell.InteractiveTB.set_mode(mode=new_mode)
2522 shell.InteractiveTB.set_mode(mode=new_mode)
2515 print 'Exception reporting mode:',shell.InteractiveTB.mode
2523 print 'Exception reporting mode:',shell.InteractiveTB.mode
2516 except:
2524 except:
2517 xmode_switch_err('user')
2525 xmode_switch_err('user')
2518
2526
2519 # threaded shells use a special handler in sys.excepthook
2527 # threaded shells use a special handler in sys.excepthook
2520 if shell.isthreaded:
2528 if shell.isthreaded:
2521 try:
2529 try:
2522 shell.sys_excepthook.set_mode(mode=new_mode)
2530 shell.sys_excepthook.set_mode(mode=new_mode)
2523 except:
2531 except:
2524 xmode_switch_err('threaded')
2532 xmode_switch_err('threaded')
2525
2533
2526 def magic_colors(self,parameter_s = ''):
2534 def magic_colors(self,parameter_s = ''):
2527 """Switch color scheme for prompts, info system and exception handlers.
2535 """Switch color scheme for prompts, info system and exception handlers.
2528
2536
2529 Currently implemented schemes: NoColor, Linux, LightBG.
2537 Currently implemented schemes: NoColor, Linux, LightBG.
2530
2538
2531 Color scheme names are not case-sensitive."""
2539 Color scheme names are not case-sensitive."""
2532
2540
2533 def color_switch_err(name):
2541 def color_switch_err(name):
2534 warn('Error changing %s color schemes.\n%s' %
2542 warn('Error changing %s color schemes.\n%s' %
2535 (name,sys.exc_info()[1]))
2543 (name,sys.exc_info()[1]))
2536
2544
2537
2545
2538 new_scheme = parameter_s.strip()
2546 new_scheme = parameter_s.strip()
2539 if not new_scheme:
2547 if not new_scheme:
2540 raise UsageError(
2548 raise UsageError(
2541 "%colors: you must specify a color scheme. See '%colors?'")
2549 "%colors: you must specify a color scheme. See '%colors?'")
2542 return
2550 return
2543 # local shortcut
2551 # local shortcut
2544 shell = self.shell
2552 shell = self.shell
2545
2553
2546 import IPython.utils.rlineimpl as readline
2554 import IPython.utils.rlineimpl as readline
2547
2555
2548 if not readline.have_readline and sys.platform == "win32":
2556 if not readline.have_readline and sys.platform == "win32":
2549 msg = """\
2557 msg = """\
2550 Proper color support under MS Windows requires the pyreadline library.
2558 Proper color support under MS Windows requires the pyreadline library.
2551 You can find it at:
2559 You can find it at:
2552 http://ipython.scipy.org/moin/PyReadline/Intro
2560 http://ipython.scipy.org/moin/PyReadline/Intro
2553 Gary's readline needs the ctypes module, from:
2561 Gary's readline needs the ctypes module, from:
2554 http://starship.python.net/crew/theller/ctypes
2562 http://starship.python.net/crew/theller/ctypes
2555 (Note that ctypes is already part of Python versions 2.5 and newer).
2563 (Note that ctypes is already part of Python versions 2.5 and newer).
2556
2564
2557 Defaulting color scheme to 'NoColor'"""
2565 Defaulting color scheme to 'NoColor'"""
2558 new_scheme = 'NoColor'
2566 new_scheme = 'NoColor'
2559 warn(msg)
2567 warn(msg)
2560
2568
2561 # readline option is 0
2569 # readline option is 0
2562 if not shell.has_readline:
2570 if not shell.has_readline:
2563 new_scheme = 'NoColor'
2571 new_scheme = 'NoColor'
2564
2572
2565 # Set prompt colors
2573 # Set prompt colors
2566 try:
2574 try:
2567 shell.outputcache.set_colors(new_scheme)
2575 shell.outputcache.set_colors(new_scheme)
2568 except:
2576 except:
2569 color_switch_err('prompt')
2577 color_switch_err('prompt')
2570 else:
2578 else:
2571 shell.colors = \
2579 shell.colors = \
2572 shell.outputcache.color_table.active_scheme_name
2580 shell.outputcache.color_table.active_scheme_name
2573 # Set exception colors
2581 # Set exception colors
2574 try:
2582 try:
2575 shell.InteractiveTB.set_colors(scheme = new_scheme)
2583 shell.InteractiveTB.set_colors(scheme = new_scheme)
2576 shell.SyntaxTB.set_colors(scheme = new_scheme)
2584 shell.SyntaxTB.set_colors(scheme = new_scheme)
2577 except:
2585 except:
2578 color_switch_err('exception')
2586 color_switch_err('exception')
2579
2587
2580 # threaded shells use a verbose traceback in sys.excepthook
2588 # threaded shells use a verbose traceback in sys.excepthook
2581 if shell.isthreaded:
2589 if shell.isthreaded:
2582 try:
2590 try:
2583 shell.sys_excepthook.set_colors(scheme=new_scheme)
2591 shell.sys_excepthook.set_colors(scheme=new_scheme)
2584 except:
2592 except:
2585 color_switch_err('system exception handler')
2593 color_switch_err('system exception handler')
2586
2594
2587 # Set info (for 'object?') colors
2595 # Set info (for 'object?') colors
2588 if shell.color_info:
2596 if shell.color_info:
2589 try:
2597 try:
2590 shell.inspector.set_active_scheme(new_scheme)
2598 shell.inspector.set_active_scheme(new_scheme)
2591 except:
2599 except:
2592 color_switch_err('object inspector')
2600 color_switch_err('object inspector')
2593 else:
2601 else:
2594 shell.inspector.set_active_scheme('NoColor')
2602 shell.inspector.set_active_scheme('NoColor')
2595
2603
2596 def magic_color_info(self,parameter_s = ''):
2604 def magic_color_info(self,parameter_s = ''):
2597 """Toggle color_info.
2605 """Toggle color_info.
2598
2606
2599 The color_info configuration parameter controls whether colors are
2607 The color_info configuration parameter controls whether colors are
2600 used for displaying object details (by things like %psource, %pfile or
2608 used for displaying object details (by things like %psource, %pfile or
2601 the '?' system). This function toggles this value with each call.
2609 the '?' system). This function toggles this value with each call.
2602
2610
2603 Note that unless you have a fairly recent pager (less works better
2611 Note that unless you have a fairly recent pager (less works better
2604 than more) in your system, using colored object information displays
2612 than more) in your system, using colored object information displays
2605 will not work properly. Test it and see."""
2613 will not work properly. Test it and see."""
2606
2614
2607 self.shell.color_info = not self.shell.color_info
2615 self.shell.color_info = not self.shell.color_info
2608 self.magic_colors(self.shell.colors)
2616 self.magic_colors(self.shell.colors)
2609 print 'Object introspection functions have now coloring:',
2617 print 'Object introspection functions have now coloring:',
2610 print ['OFF','ON'][int(self.shell.color_info)]
2618 print ['OFF','ON'][int(self.shell.color_info)]
2611
2619
2612 def magic_Pprint(self, parameter_s=''):
2620 def magic_Pprint(self, parameter_s=''):
2613 """Toggle pretty printing on/off."""
2621 """Toggle pretty printing on/off."""
2614
2622
2615 self.shell.pprint = 1 - self.shell.pprint
2623 self.shell.pprint = 1 - self.shell.pprint
2616 print 'Pretty printing has been turned', \
2624 print 'Pretty printing has been turned', \
2617 ['OFF','ON'][self.shell.pprint]
2625 ['OFF','ON'][self.shell.pprint]
2618
2626
2619 def magic_Exit(self, parameter_s=''):
2627 def magic_Exit(self, parameter_s=''):
2620 """Exit IPython without confirmation."""
2628 """Exit IPython without confirmation."""
2621
2629
2622 self.shell.ask_exit()
2630 self.shell.ask_exit()
2623
2631
2624 # Add aliases as magics so all common forms work: exit, quit, Exit, Quit.
2632 # Add aliases as magics so all common forms work: exit, quit, Exit, Quit.
2625 magic_exit = magic_quit = magic_Quit = magic_Exit
2633 magic_exit = magic_quit = magic_Quit = magic_Exit
2626
2634
2627 #......................................................................
2635 #......................................................................
2628 # Functions to implement unix shell-type things
2636 # Functions to implement unix shell-type things
2629
2637
2630 @testdec.skip_doctest
2638 @testdec.skip_doctest
2631 def magic_alias(self, parameter_s = ''):
2639 def magic_alias(self, parameter_s = ''):
2632 """Define an alias for a system command.
2640 """Define an alias for a system command.
2633
2641
2634 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2642 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2635
2643
2636 Then, typing 'alias_name params' will execute the system command 'cmd
2644 Then, typing 'alias_name params' will execute the system command 'cmd
2637 params' (from your underlying operating system).
2645 params' (from your underlying operating system).
2638
2646
2639 Aliases have lower precedence than magic functions and Python normal
2647 Aliases have lower precedence than magic functions and Python normal
2640 variables, so if 'foo' is both a Python variable and an alias, the
2648 variables, so if 'foo' is both a Python variable and an alias, the
2641 alias can not be executed until 'del foo' removes the Python variable.
2649 alias can not be executed until 'del foo' removes the Python variable.
2642
2650
2643 You can use the %l specifier in an alias definition to represent the
2651 You can use the %l specifier in an alias definition to represent the
2644 whole line when the alias is called. For example:
2652 whole line when the alias is called. For example:
2645
2653
2646 In [2]: alias all echo "Input in brackets: <%l>"
2654 In [2]: alias all echo "Input in brackets: <%l>"
2647 In [3]: all hello world
2655 In [3]: all hello world
2648 Input in brackets: <hello world>
2656 Input in brackets: <hello world>
2649
2657
2650 You can also define aliases with parameters using %s specifiers (one
2658 You can also define aliases with parameters using %s specifiers (one
2651 per parameter):
2659 per parameter):
2652
2660
2653 In [1]: alias parts echo first %s second %s
2661 In [1]: alias parts echo first %s second %s
2654 In [2]: %parts A B
2662 In [2]: %parts A B
2655 first A second B
2663 first A second B
2656 In [3]: %parts A
2664 In [3]: %parts A
2657 Incorrect number of arguments: 2 expected.
2665 Incorrect number of arguments: 2 expected.
2658 parts is an alias to: 'echo first %s second %s'
2666 parts is an alias to: 'echo first %s second %s'
2659
2667
2660 Note that %l and %s are mutually exclusive. You can only use one or
2668 Note that %l and %s are mutually exclusive. You can only use one or
2661 the other in your aliases.
2669 the other in your aliases.
2662
2670
2663 Aliases expand Python variables just like system calls using ! or !!
2671 Aliases expand Python variables just like system calls using ! or !!
2664 do: all expressions prefixed with '$' get expanded. For details of
2672 do: all expressions prefixed with '$' get expanded. For details of
2665 the semantic rules, see PEP-215:
2673 the semantic rules, see PEP-215:
2666 http://www.python.org/peps/pep-0215.html. This is the library used by
2674 http://www.python.org/peps/pep-0215.html. This is the library used by
2667 IPython for variable expansion. If you want to access a true shell
2675 IPython for variable expansion. If you want to access a true shell
2668 variable, an extra $ is necessary to prevent its expansion by IPython:
2676 variable, an extra $ is necessary to prevent its expansion by IPython:
2669
2677
2670 In [6]: alias show echo
2678 In [6]: alias show echo
2671 In [7]: PATH='A Python string'
2679 In [7]: PATH='A Python string'
2672 In [8]: show $PATH
2680 In [8]: show $PATH
2673 A Python string
2681 A Python string
2674 In [9]: show $$PATH
2682 In [9]: show $$PATH
2675 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2683 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2676
2684
2677 You can use the alias facility to acess all of $PATH. See the %rehash
2685 You can use the alias facility to acess all of $PATH. See the %rehash
2678 and %rehashx functions, which automatically create aliases for the
2686 and %rehashx functions, which automatically create aliases for the
2679 contents of your $PATH.
2687 contents of your $PATH.
2680
2688
2681 If called with no parameters, %alias prints the current alias table."""
2689 If called with no parameters, %alias prints the current alias table."""
2682
2690
2683 par = parameter_s.strip()
2691 par = parameter_s.strip()
2684 if not par:
2692 if not par:
2685 stored = self.db.get('stored_aliases', {} )
2693 stored = self.db.get('stored_aliases', {} )
2686 aliases = sorted(self.shell.alias_manager.aliases)
2694 aliases = sorted(self.shell.alias_manager.aliases)
2687 # for k, v in stored:
2695 # for k, v in stored:
2688 # atab.append(k, v[0])
2696 # atab.append(k, v[0])
2689
2697
2690 print "Total number of aliases:", len(aliases)
2698 print "Total number of aliases:", len(aliases)
2691 return aliases
2699 return aliases
2692
2700
2693 # Now try to define a new one
2701 # Now try to define a new one
2694 try:
2702 try:
2695 alias,cmd = par.split(None, 1)
2703 alias,cmd = par.split(None, 1)
2696 except:
2704 except:
2697 print oinspect.getdoc(self.magic_alias)
2705 print oinspect.getdoc(self.magic_alias)
2698 else:
2706 else:
2699 self.shell.alias_manager.soft_define_alias(alias, cmd)
2707 self.shell.alias_manager.soft_define_alias(alias, cmd)
2700 # end magic_alias
2708 # end magic_alias
2701
2709
2702 def magic_unalias(self, parameter_s = ''):
2710 def magic_unalias(self, parameter_s = ''):
2703 """Remove an alias"""
2711 """Remove an alias"""
2704
2712
2705 aname = parameter_s.strip()
2713 aname = parameter_s.strip()
2706 self.shell.alias_manager.undefine_alias(aname)
2714 self.shell.alias_manager.undefine_alias(aname)
2707 stored = self.db.get('stored_aliases', {} )
2715 stored = self.db.get('stored_aliases', {} )
2708 if aname in stored:
2716 if aname in stored:
2709 print "Removing %stored alias",aname
2717 print "Removing %stored alias",aname
2710 del stored[aname]
2718 del stored[aname]
2711 self.db['stored_aliases'] = stored
2719 self.db['stored_aliases'] = stored
2712
2720
2713
2721
2714 def magic_rehashx(self, parameter_s = ''):
2722 def magic_rehashx(self, parameter_s = ''):
2715 """Update the alias table with all executable files in $PATH.
2723 """Update the alias table with all executable files in $PATH.
2716
2724
2717 This version explicitly checks that every entry in $PATH is a file
2725 This version explicitly checks that every entry in $PATH is a file
2718 with execute access (os.X_OK), so it is much slower than %rehash.
2726 with execute access (os.X_OK), so it is much slower than %rehash.
2719
2727
2720 Under Windows, it checks executability as a match agains a
2728 Under Windows, it checks executability as a match agains a
2721 '|'-separated string of extensions, stored in the IPython config
2729 '|'-separated string of extensions, stored in the IPython config
2722 variable win_exec_ext. This defaults to 'exe|com|bat'.
2730 variable win_exec_ext. This defaults to 'exe|com|bat'.
2723
2731
2724 This function also resets the root module cache of module completer,
2732 This function also resets the root module cache of module completer,
2725 used on slow filesystems.
2733 used on slow filesystems.
2726 """
2734 """
2727 from IPython.core.alias import InvalidAliasError
2735 from IPython.core.alias import InvalidAliasError
2728
2736
2729 # for the benefit of module completer in ipy_completers.py
2737 # for the benefit of module completer in ipy_completers.py
2730 del self.db['rootmodules']
2738 del self.db['rootmodules']
2731
2739
2732 path = [os.path.abspath(os.path.expanduser(p)) for p in
2740 path = [os.path.abspath(os.path.expanduser(p)) for p in
2733 os.environ.get('PATH','').split(os.pathsep)]
2741 os.environ.get('PATH','').split(os.pathsep)]
2734 path = filter(os.path.isdir,path)
2742 path = filter(os.path.isdir,path)
2735
2743
2736 syscmdlist = []
2744 syscmdlist = []
2737 # Now define isexec in a cross platform manner.
2745 # Now define isexec in a cross platform manner.
2738 if os.name == 'posix':
2746 if os.name == 'posix':
2739 isexec = lambda fname:os.path.isfile(fname) and \
2747 isexec = lambda fname:os.path.isfile(fname) and \
2740 os.access(fname,os.X_OK)
2748 os.access(fname,os.X_OK)
2741 else:
2749 else:
2742 try:
2750 try:
2743 winext = os.environ['pathext'].replace(';','|').replace('.','')
2751 winext = os.environ['pathext'].replace(';','|').replace('.','')
2744 except KeyError:
2752 except KeyError:
2745 winext = 'exe|com|bat|py'
2753 winext = 'exe|com|bat|py'
2746 if 'py' not in winext:
2754 if 'py' not in winext:
2747 winext += '|py'
2755 winext += '|py'
2748 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2756 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2749 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2757 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2750 savedir = os.getcwd()
2758 savedir = os.getcwd()
2751
2759
2752 # Now walk the paths looking for executables to alias.
2760 # Now walk the paths looking for executables to alias.
2753 try:
2761 try:
2754 # write the whole loop for posix/Windows so we don't have an if in
2762 # write the whole loop for posix/Windows so we don't have an if in
2755 # the innermost part
2763 # the innermost part
2756 if os.name == 'posix':
2764 if os.name == 'posix':
2757 for pdir in path:
2765 for pdir in path:
2758 os.chdir(pdir)
2766 os.chdir(pdir)
2759 for ff in os.listdir(pdir):
2767 for ff in os.listdir(pdir):
2760 if isexec(ff):
2768 if isexec(ff):
2761 try:
2769 try:
2762 # Removes dots from the name since ipython
2770 # Removes dots from the name since ipython
2763 # will assume names with dots to be python.
2771 # will assume names with dots to be python.
2764 self.shell.alias_manager.define_alias(
2772 self.shell.alias_manager.define_alias(
2765 ff.replace('.',''), ff)
2773 ff.replace('.',''), ff)
2766 except InvalidAliasError:
2774 except InvalidAliasError:
2767 pass
2775 pass
2768 else:
2776 else:
2769 syscmdlist.append(ff)
2777 syscmdlist.append(ff)
2770 else:
2778 else:
2771 no_alias = self.shell.alias_manager.no_alias
2779 no_alias = self.shell.alias_manager.no_alias
2772 for pdir in path:
2780 for pdir in path:
2773 os.chdir(pdir)
2781 os.chdir(pdir)
2774 for ff in os.listdir(pdir):
2782 for ff in os.listdir(pdir):
2775 base, ext = os.path.splitext(ff)
2783 base, ext = os.path.splitext(ff)
2776 if isexec(ff) and base.lower() not in no_alias:
2784 if isexec(ff) and base.lower() not in no_alias:
2777 if ext.lower() == '.exe':
2785 if ext.lower() == '.exe':
2778 ff = base
2786 ff = base
2779 try:
2787 try:
2780 # Removes dots from the name since ipython
2788 # Removes dots from the name since ipython
2781 # will assume names with dots to be python.
2789 # will assume names with dots to be python.
2782 self.shell.alias_manager.define_alias(
2790 self.shell.alias_manager.define_alias(
2783 base.lower().replace('.',''), ff)
2791 base.lower().replace('.',''), ff)
2784 except InvalidAliasError:
2792 except InvalidAliasError:
2785 pass
2793 pass
2786 syscmdlist.append(ff)
2794 syscmdlist.append(ff)
2787 db = self.db
2795 db = self.db
2788 db['syscmdlist'] = syscmdlist
2796 db['syscmdlist'] = syscmdlist
2789 finally:
2797 finally:
2790 os.chdir(savedir)
2798 os.chdir(savedir)
2791
2799
2792 def magic_pwd(self, parameter_s = ''):
2800 def magic_pwd(self, parameter_s = ''):
2793 """Return the current working directory path."""
2801 """Return the current working directory path."""
2794 return os.getcwd()
2802 return os.getcwd()
2795
2803
2796 def magic_cd(self, parameter_s=''):
2804 def magic_cd(self, parameter_s=''):
2797 """Change the current working directory.
2805 """Change the current working directory.
2798
2806
2799 This command automatically maintains an internal list of directories
2807 This command automatically maintains an internal list of directories
2800 you visit during your IPython session, in the variable _dh. The
2808 you visit during your IPython session, in the variable _dh. The
2801 command %dhist shows this history nicely formatted. You can also
2809 command %dhist shows this history nicely formatted. You can also
2802 do 'cd -<tab>' to see directory history conveniently.
2810 do 'cd -<tab>' to see directory history conveniently.
2803
2811
2804 Usage:
2812 Usage:
2805
2813
2806 cd 'dir': changes to directory 'dir'.
2814 cd 'dir': changes to directory 'dir'.
2807
2815
2808 cd -: changes to the last visited directory.
2816 cd -: changes to the last visited directory.
2809
2817
2810 cd -<n>: changes to the n-th directory in the directory history.
2818 cd -<n>: changes to the n-th directory in the directory history.
2811
2819
2812 cd --foo: change to directory that matches 'foo' in history
2820 cd --foo: change to directory that matches 'foo' in history
2813
2821
2814 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2822 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2815 (note: cd <bookmark_name> is enough if there is no
2823 (note: cd <bookmark_name> is enough if there is no
2816 directory <bookmark_name>, but a bookmark with the name exists.)
2824 directory <bookmark_name>, but a bookmark with the name exists.)
2817 'cd -b <tab>' allows you to tab-complete bookmark names.
2825 'cd -b <tab>' allows you to tab-complete bookmark names.
2818
2826
2819 Options:
2827 Options:
2820
2828
2821 -q: quiet. Do not print the working directory after the cd command is
2829 -q: quiet. Do not print the working directory after the cd command is
2822 executed. By default IPython's cd command does print this directory,
2830 executed. By default IPython's cd command does print this directory,
2823 since the default prompts do not display path information.
2831 since the default prompts do not display path information.
2824
2832
2825 Note that !cd doesn't work for this purpose because the shell where
2833 Note that !cd doesn't work for this purpose because the shell where
2826 !command runs is immediately discarded after executing 'command'."""
2834 !command runs is immediately discarded after executing 'command'."""
2827
2835
2828 parameter_s = parameter_s.strip()
2836 parameter_s = parameter_s.strip()
2829 #bkms = self.shell.persist.get("bookmarks",{})
2837 #bkms = self.shell.persist.get("bookmarks",{})
2830
2838
2831 oldcwd = os.getcwd()
2839 oldcwd = os.getcwd()
2832 numcd = re.match(r'(-)(\d+)$',parameter_s)
2840 numcd = re.match(r'(-)(\d+)$',parameter_s)
2833 # jump in directory history by number
2841 # jump in directory history by number
2834 if numcd:
2842 if numcd:
2835 nn = int(numcd.group(2))
2843 nn = int(numcd.group(2))
2836 try:
2844 try:
2837 ps = self.shell.user_ns['_dh'][nn]
2845 ps = self.shell.user_ns['_dh'][nn]
2838 except IndexError:
2846 except IndexError:
2839 print 'The requested directory does not exist in history.'
2847 print 'The requested directory does not exist in history.'
2840 return
2848 return
2841 else:
2849 else:
2842 opts = {}
2850 opts = {}
2843 elif parameter_s.startswith('--'):
2851 elif parameter_s.startswith('--'):
2844 ps = None
2852 ps = None
2845 fallback = None
2853 fallback = None
2846 pat = parameter_s[2:]
2854 pat = parameter_s[2:]
2847 dh = self.shell.user_ns['_dh']
2855 dh = self.shell.user_ns['_dh']
2848 # first search only by basename (last component)
2856 # first search only by basename (last component)
2849 for ent in reversed(dh):
2857 for ent in reversed(dh):
2850 if pat in os.path.basename(ent) and os.path.isdir(ent):
2858 if pat in os.path.basename(ent) and os.path.isdir(ent):
2851 ps = ent
2859 ps = ent
2852 break
2860 break
2853
2861
2854 if fallback is None and pat in ent and os.path.isdir(ent):
2862 if fallback is None and pat in ent and os.path.isdir(ent):
2855 fallback = ent
2863 fallback = ent
2856
2864
2857 # if we have no last part match, pick the first full path match
2865 # if we have no last part match, pick the first full path match
2858 if ps is None:
2866 if ps is None:
2859 ps = fallback
2867 ps = fallback
2860
2868
2861 if ps is None:
2869 if ps is None:
2862 print "No matching entry in directory history"
2870 print "No matching entry in directory history"
2863 return
2871 return
2864 else:
2872 else:
2865 opts = {}
2873 opts = {}
2866
2874
2867
2875
2868 else:
2876 else:
2869 #turn all non-space-escaping backslashes to slashes,
2877 #turn all non-space-escaping backslashes to slashes,
2870 # for c:\windows\directory\names\
2878 # for c:\windows\directory\names\
2871 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2879 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2872 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2880 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2873 # jump to previous
2881 # jump to previous
2874 if ps == '-':
2882 if ps == '-':
2875 try:
2883 try:
2876 ps = self.shell.user_ns['_dh'][-2]
2884 ps = self.shell.user_ns['_dh'][-2]
2877 except IndexError:
2885 except IndexError:
2878 raise UsageError('%cd -: No previous directory to change to.')
2886 raise UsageError('%cd -: No previous directory to change to.')
2879 # jump to bookmark if needed
2887 # jump to bookmark if needed
2880 else:
2888 else:
2881 if not os.path.isdir(ps) or opts.has_key('b'):
2889 if not os.path.isdir(ps) or opts.has_key('b'):
2882 bkms = self.db.get('bookmarks', {})
2890 bkms = self.db.get('bookmarks', {})
2883
2891
2884 if bkms.has_key(ps):
2892 if bkms.has_key(ps):
2885 target = bkms[ps]
2893 target = bkms[ps]
2886 print '(bookmark:%s) -> %s' % (ps,target)
2894 print '(bookmark:%s) -> %s' % (ps,target)
2887 ps = target
2895 ps = target
2888 else:
2896 else:
2889 if opts.has_key('b'):
2897 if opts.has_key('b'):
2890 raise UsageError("Bookmark '%s' not found. "
2898 raise UsageError("Bookmark '%s' not found. "
2891 "Use '%%bookmark -l' to see your bookmarks." % ps)
2899 "Use '%%bookmark -l' to see your bookmarks." % ps)
2892
2900
2893 # at this point ps should point to the target dir
2901 # at this point ps should point to the target dir
2894 if ps:
2902 if ps:
2895 try:
2903 try:
2896 os.chdir(os.path.expanduser(ps))
2904 os.chdir(os.path.expanduser(ps))
2897 if self.shell.term_title:
2905 if self.shell.term_title:
2898 set_term_title('IPython: ' + abbrev_cwd())
2906 set_term_title('IPython: ' + abbrev_cwd())
2899 except OSError:
2907 except OSError:
2900 print sys.exc_info()[1]
2908 print sys.exc_info()[1]
2901 else:
2909 else:
2902 cwd = os.getcwd()
2910 cwd = os.getcwd()
2903 dhist = self.shell.user_ns['_dh']
2911 dhist = self.shell.user_ns['_dh']
2904 if oldcwd != cwd:
2912 if oldcwd != cwd:
2905 dhist.append(cwd)
2913 dhist.append(cwd)
2906 self.db['dhist'] = compress_dhist(dhist)[-100:]
2914 self.db['dhist'] = compress_dhist(dhist)[-100:]
2907
2915
2908 else:
2916 else:
2909 os.chdir(self.shell.home_dir)
2917 os.chdir(self.shell.home_dir)
2910 if self.shell.term_title:
2918 if self.shell.term_title:
2911 set_term_title('IPython: ' + '~')
2919 set_term_title('IPython: ' + '~')
2912 cwd = os.getcwd()
2920 cwd = os.getcwd()
2913 dhist = self.shell.user_ns['_dh']
2921 dhist = self.shell.user_ns['_dh']
2914
2922
2915 if oldcwd != cwd:
2923 if oldcwd != cwd:
2916 dhist.append(cwd)
2924 dhist.append(cwd)
2917 self.db['dhist'] = compress_dhist(dhist)[-100:]
2925 self.db['dhist'] = compress_dhist(dhist)[-100:]
2918 if not 'q' in opts and self.shell.user_ns['_dh']:
2926 if not 'q' in opts and self.shell.user_ns['_dh']:
2919 print self.shell.user_ns['_dh'][-1]
2927 print self.shell.user_ns['_dh'][-1]
2920
2928
2921
2929
2922 def magic_env(self, parameter_s=''):
2930 def magic_env(self, parameter_s=''):
2923 """List environment variables."""
2931 """List environment variables."""
2924
2932
2925 return os.environ.data
2933 return os.environ.data
2926
2934
2927 def magic_pushd(self, parameter_s=''):
2935 def magic_pushd(self, parameter_s=''):
2928 """Place the current dir on stack and change directory.
2936 """Place the current dir on stack and change directory.
2929
2937
2930 Usage:\\
2938 Usage:\\
2931 %pushd ['dirname']
2939 %pushd ['dirname']
2932 """
2940 """
2933
2941
2934 dir_s = self.shell.dir_stack
2942 dir_s = self.shell.dir_stack
2935 tgt = os.path.expanduser(parameter_s)
2943 tgt = os.path.expanduser(parameter_s)
2936 cwd = os.getcwd().replace(self.home_dir,'~')
2944 cwd = os.getcwd().replace(self.home_dir,'~')
2937 if tgt:
2945 if tgt:
2938 self.magic_cd(parameter_s)
2946 self.magic_cd(parameter_s)
2939 dir_s.insert(0,cwd)
2947 dir_s.insert(0,cwd)
2940 return self.magic_dirs()
2948 return self.magic_dirs()
2941
2949
2942 def magic_popd(self, parameter_s=''):
2950 def magic_popd(self, parameter_s=''):
2943 """Change to directory popped off the top of the stack.
2951 """Change to directory popped off the top of the stack.
2944 """
2952 """
2945 if not self.shell.dir_stack:
2953 if not self.shell.dir_stack:
2946 raise UsageError("%popd on empty stack")
2954 raise UsageError("%popd on empty stack")
2947 top = self.shell.dir_stack.pop(0)
2955 top = self.shell.dir_stack.pop(0)
2948 self.magic_cd(top)
2956 self.magic_cd(top)
2949 print "popd ->",top
2957 print "popd ->",top
2950
2958
2951 def magic_dirs(self, parameter_s=''):
2959 def magic_dirs(self, parameter_s=''):
2952 """Return the current directory stack."""
2960 """Return the current directory stack."""
2953
2961
2954 return self.shell.dir_stack
2962 return self.shell.dir_stack
2955
2963
2956 def magic_dhist(self, parameter_s=''):
2964 def magic_dhist(self, parameter_s=''):
2957 """Print your history of visited directories.
2965 """Print your history of visited directories.
2958
2966
2959 %dhist -> print full history\\
2967 %dhist -> print full history\\
2960 %dhist n -> print last n entries only\\
2968 %dhist n -> print last n entries only\\
2961 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2969 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2962
2970
2963 This history is automatically maintained by the %cd command, and
2971 This history is automatically maintained by the %cd command, and
2964 always available as the global list variable _dh. You can use %cd -<n>
2972 always available as the global list variable _dh. You can use %cd -<n>
2965 to go to directory number <n>.
2973 to go to directory number <n>.
2966
2974
2967 Note that most of time, you should view directory history by entering
2975 Note that most of time, you should view directory history by entering
2968 cd -<TAB>.
2976 cd -<TAB>.
2969
2977
2970 """
2978 """
2971
2979
2972 dh = self.shell.user_ns['_dh']
2980 dh = self.shell.user_ns['_dh']
2973 if parameter_s:
2981 if parameter_s:
2974 try:
2982 try:
2975 args = map(int,parameter_s.split())
2983 args = map(int,parameter_s.split())
2976 except:
2984 except:
2977 self.arg_err(Magic.magic_dhist)
2985 self.arg_err(Magic.magic_dhist)
2978 return
2986 return
2979 if len(args) == 1:
2987 if len(args) == 1:
2980 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2988 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2981 elif len(args) == 2:
2989 elif len(args) == 2:
2982 ini,fin = args
2990 ini,fin = args
2983 else:
2991 else:
2984 self.arg_err(Magic.magic_dhist)
2992 self.arg_err(Magic.magic_dhist)
2985 return
2993 return
2986 else:
2994 else:
2987 ini,fin = 0,len(dh)
2995 ini,fin = 0,len(dh)
2988 nlprint(dh,
2996 nlprint(dh,
2989 header = 'Directory history (kept in _dh)',
2997 header = 'Directory history (kept in _dh)',
2990 start=ini,stop=fin)
2998 start=ini,stop=fin)
2991
2999
2992 @testdec.skip_doctest
3000 @testdec.skip_doctest
2993 def magic_sc(self, parameter_s=''):
3001 def magic_sc(self, parameter_s=''):
2994 """Shell capture - execute a shell command and capture its output.
3002 """Shell capture - execute a shell command and capture its output.
2995
3003
2996 DEPRECATED. Suboptimal, retained for backwards compatibility.
3004 DEPRECATED. Suboptimal, retained for backwards compatibility.
2997
3005
2998 You should use the form 'var = !command' instead. Example:
3006 You should use the form 'var = !command' instead. Example:
2999
3007
3000 "%sc -l myfiles = ls ~" should now be written as
3008 "%sc -l myfiles = ls ~" should now be written as
3001
3009
3002 "myfiles = !ls ~"
3010 "myfiles = !ls ~"
3003
3011
3004 myfiles.s, myfiles.l and myfiles.n still apply as documented
3012 myfiles.s, myfiles.l and myfiles.n still apply as documented
3005 below.
3013 below.
3006
3014
3007 --
3015 --
3008 %sc [options] varname=command
3016 %sc [options] varname=command
3009
3017
3010 IPython will run the given command using commands.getoutput(), and
3018 IPython will run the given command using commands.getoutput(), and
3011 will then update the user's interactive namespace with a variable
3019 will then update the user's interactive namespace with a variable
3012 called varname, containing the value of the call. Your command can
3020 called varname, containing the value of the call. Your command can
3013 contain shell wildcards, pipes, etc.
3021 contain shell wildcards, pipes, etc.
3014
3022
3015 The '=' sign in the syntax is mandatory, and the variable name you
3023 The '=' sign in the syntax is mandatory, and the variable name you
3016 supply must follow Python's standard conventions for valid names.
3024 supply must follow Python's standard conventions for valid names.
3017
3025
3018 (A special format without variable name exists for internal use)
3026 (A special format without variable name exists for internal use)
3019
3027
3020 Options:
3028 Options:
3021
3029
3022 -l: list output. Split the output on newlines into a list before
3030 -l: list output. Split the output on newlines into a list before
3023 assigning it to the given variable. By default the output is stored
3031 assigning it to the given variable. By default the output is stored
3024 as a single string.
3032 as a single string.
3025
3033
3026 -v: verbose. Print the contents of the variable.
3034 -v: verbose. Print the contents of the variable.
3027
3035
3028 In most cases you should not need to split as a list, because the
3036 In most cases you should not need to split as a list, because the
3029 returned value is a special type of string which can automatically
3037 returned value is a special type of string which can automatically
3030 provide its contents either as a list (split on newlines) or as a
3038 provide its contents either as a list (split on newlines) or as a
3031 space-separated string. These are convenient, respectively, either
3039 space-separated string. These are convenient, respectively, either
3032 for sequential processing or to be passed to a shell command.
3040 for sequential processing or to be passed to a shell command.
3033
3041
3034 For example:
3042 For example:
3035
3043
3036 # all-random
3044 # all-random
3037
3045
3038 # Capture into variable a
3046 # Capture into variable a
3039 In [1]: sc a=ls *py
3047 In [1]: sc a=ls *py
3040
3048
3041 # a is a string with embedded newlines
3049 # a is a string with embedded newlines
3042 In [2]: a
3050 In [2]: a
3043 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
3051 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
3044
3052
3045 # which can be seen as a list:
3053 # which can be seen as a list:
3046 In [3]: a.l
3054 In [3]: a.l
3047 Out[3]: ['setup.py', 'win32_manual_post_install.py']
3055 Out[3]: ['setup.py', 'win32_manual_post_install.py']
3048
3056
3049 # or as a whitespace-separated string:
3057 # or as a whitespace-separated string:
3050 In [4]: a.s
3058 In [4]: a.s
3051 Out[4]: 'setup.py win32_manual_post_install.py'
3059 Out[4]: 'setup.py win32_manual_post_install.py'
3052
3060
3053 # a.s is useful to pass as a single command line:
3061 # a.s is useful to pass as a single command line:
3054 In [5]: !wc -l $a.s
3062 In [5]: !wc -l $a.s
3055 146 setup.py
3063 146 setup.py
3056 130 win32_manual_post_install.py
3064 130 win32_manual_post_install.py
3057 276 total
3065 276 total
3058
3066
3059 # while the list form is useful to loop over:
3067 # while the list form is useful to loop over:
3060 In [6]: for f in a.l:
3068 In [6]: for f in a.l:
3061 ...: !wc -l $f
3069 ...: !wc -l $f
3062 ...:
3070 ...:
3063 146 setup.py
3071 146 setup.py
3064 130 win32_manual_post_install.py
3072 130 win32_manual_post_install.py
3065
3073
3066 Similiarly, the lists returned by the -l option are also special, in
3074 Similiarly, the lists returned by the -l option are also special, in
3067 the sense that you can equally invoke the .s attribute on them to
3075 the sense that you can equally invoke the .s attribute on them to
3068 automatically get a whitespace-separated string from their contents:
3076 automatically get a whitespace-separated string from their contents:
3069
3077
3070 In [7]: sc -l b=ls *py
3078 In [7]: sc -l b=ls *py
3071
3079
3072 In [8]: b
3080 In [8]: b
3073 Out[8]: ['setup.py', 'win32_manual_post_install.py']
3081 Out[8]: ['setup.py', 'win32_manual_post_install.py']
3074
3082
3075 In [9]: b.s
3083 In [9]: b.s
3076 Out[9]: 'setup.py win32_manual_post_install.py'
3084 Out[9]: 'setup.py win32_manual_post_install.py'
3077
3085
3078 In summary, both the lists and strings used for ouptut capture have
3086 In summary, both the lists and strings used for ouptut capture have
3079 the following special attributes:
3087 the following special attributes:
3080
3088
3081 .l (or .list) : value as list.
3089 .l (or .list) : value as list.
3082 .n (or .nlstr): value as newline-separated string.
3090 .n (or .nlstr): value as newline-separated string.
3083 .s (or .spstr): value as space-separated string.
3091 .s (or .spstr): value as space-separated string.
3084 """
3092 """
3085
3093
3086 opts,args = self.parse_options(parameter_s,'lv')
3094 opts,args = self.parse_options(parameter_s,'lv')
3087 # Try to get a variable name and command to run
3095 # Try to get a variable name and command to run
3088 try:
3096 try:
3089 # the variable name must be obtained from the parse_options
3097 # the variable name must be obtained from the parse_options
3090 # output, which uses shlex.split to strip options out.
3098 # output, which uses shlex.split to strip options out.
3091 var,_ = args.split('=',1)
3099 var,_ = args.split('=',1)
3092 var = var.strip()
3100 var = var.strip()
3093 # But the the command has to be extracted from the original input
3101 # But the the command has to be extracted from the original input
3094 # parameter_s, not on what parse_options returns, to avoid the
3102 # parameter_s, not on what parse_options returns, to avoid the
3095 # quote stripping which shlex.split performs on it.
3103 # quote stripping which shlex.split performs on it.
3096 _,cmd = parameter_s.split('=',1)
3104 _,cmd = parameter_s.split('=',1)
3097 except ValueError:
3105 except ValueError:
3098 var,cmd = '',''
3106 var,cmd = '',''
3099 # If all looks ok, proceed
3107 # If all looks ok, proceed
3100 out,err = self.shell.getoutputerror(cmd)
3108 out,err = self.shell.getoutputerror(cmd)
3101 if err:
3109 if err:
3102 print >> Term.cerr,err
3110 print >> Term.cerr,err
3103 if opts.has_key('l'):
3111 if opts.has_key('l'):
3104 out = SList(out.split('\n'))
3112 out = SList(out.split('\n'))
3105 else:
3113 else:
3106 out = LSString(out)
3114 out = LSString(out)
3107 if opts.has_key('v'):
3115 if opts.has_key('v'):
3108 print '%s ==\n%s' % (var,pformat(out))
3116 print '%s ==\n%s' % (var,pformat(out))
3109 if var:
3117 if var:
3110 self.shell.user_ns.update({var:out})
3118 self.shell.user_ns.update({var:out})
3111 else:
3119 else:
3112 return out
3120 return out
3113
3121
3114 def magic_sx(self, parameter_s=''):
3122 def magic_sx(self, parameter_s=''):
3115 """Shell execute - run a shell command and capture its output.
3123 """Shell execute - run a shell command and capture its output.
3116
3124
3117 %sx command
3125 %sx command
3118
3126
3119 IPython will run the given command using commands.getoutput(), and
3127 IPython will run the given command using commands.getoutput(), and
3120 return the result formatted as a list (split on '\\n'). Since the
3128 return the result formatted as a list (split on '\\n'). Since the
3121 output is _returned_, it will be stored in ipython's regular output
3129 output is _returned_, it will be stored in ipython's regular output
3122 cache Out[N] and in the '_N' automatic variables.
3130 cache Out[N] and in the '_N' automatic variables.
3123
3131
3124 Notes:
3132 Notes:
3125
3133
3126 1) If an input line begins with '!!', then %sx is automatically
3134 1) If an input line begins with '!!', then %sx is automatically
3127 invoked. That is, while:
3135 invoked. That is, while:
3128 !ls
3136 !ls
3129 causes ipython to simply issue system('ls'), typing
3137 causes ipython to simply issue system('ls'), typing
3130 !!ls
3138 !!ls
3131 is a shorthand equivalent to:
3139 is a shorthand equivalent to:
3132 %sx ls
3140 %sx ls
3133
3141
3134 2) %sx differs from %sc in that %sx automatically splits into a list,
3142 2) %sx differs from %sc in that %sx automatically splits into a list,
3135 like '%sc -l'. The reason for this is to make it as easy as possible
3143 like '%sc -l'. The reason for this is to make it as easy as possible
3136 to process line-oriented shell output via further python commands.
3144 to process line-oriented shell output via further python commands.
3137 %sc is meant to provide much finer control, but requires more
3145 %sc is meant to provide much finer control, but requires more
3138 typing.
3146 typing.
3139
3147
3140 3) Just like %sc -l, this is a list with special attributes:
3148 3) Just like %sc -l, this is a list with special attributes:
3141
3149
3142 .l (or .list) : value as list.
3150 .l (or .list) : value as list.
3143 .n (or .nlstr): value as newline-separated string.
3151 .n (or .nlstr): value as newline-separated string.
3144 .s (or .spstr): value as whitespace-separated string.
3152 .s (or .spstr): value as whitespace-separated string.
3145
3153
3146 This is very useful when trying to use such lists as arguments to
3154 This is very useful when trying to use such lists as arguments to
3147 system commands."""
3155 system commands."""
3148
3156
3149 if parameter_s:
3157 if parameter_s:
3150 out,err = self.shell.getoutputerror(parameter_s)
3158 out,err = self.shell.getoutputerror(parameter_s)
3151 if err:
3159 if err:
3152 print >> Term.cerr,err
3160 print >> Term.cerr,err
3153 return SList(out.split('\n'))
3161 return SList(out.split('\n'))
3154
3162
3155 def magic_bg(self, parameter_s=''):
3163 def magic_bg(self, parameter_s=''):
3156 """Run a job in the background, in a separate thread.
3164 """Run a job in the background, in a separate thread.
3157
3165
3158 For example,
3166 For example,
3159
3167
3160 %bg myfunc(x,y,z=1)
3168 %bg myfunc(x,y,z=1)
3161
3169
3162 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
3170 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
3163 execution starts, a message will be printed indicating the job
3171 execution starts, a message will be printed indicating the job
3164 number. If your job number is 5, you can use
3172 number. If your job number is 5, you can use
3165
3173
3166 myvar = jobs.result(5) or myvar = jobs[5].result
3174 myvar = jobs.result(5) or myvar = jobs[5].result
3167
3175
3168 to assign this result to variable 'myvar'.
3176 to assign this result to variable 'myvar'.
3169
3177
3170 IPython has a job manager, accessible via the 'jobs' object. You can
3178 IPython has a job manager, accessible via the 'jobs' object. You can
3171 type jobs? to get more information about it, and use jobs.<TAB> to see
3179 type jobs? to get more information about it, and use jobs.<TAB> to see
3172 its attributes. All attributes not starting with an underscore are
3180 its attributes. All attributes not starting with an underscore are
3173 meant for public use.
3181 meant for public use.
3174
3182
3175 In particular, look at the jobs.new() method, which is used to create
3183 In particular, look at the jobs.new() method, which is used to create
3176 new jobs. This magic %bg function is just a convenience wrapper
3184 new jobs. This magic %bg function is just a convenience wrapper
3177 around jobs.new(), for expression-based jobs. If you want to create a
3185 around jobs.new(), for expression-based jobs. If you want to create a
3178 new job with an explicit function object and arguments, you must call
3186 new job with an explicit function object and arguments, you must call
3179 jobs.new() directly.
3187 jobs.new() directly.
3180
3188
3181 The jobs.new docstring also describes in detail several important
3189 The jobs.new docstring also describes in detail several important
3182 caveats associated with a thread-based model for background job
3190 caveats associated with a thread-based model for background job
3183 execution. Type jobs.new? for details.
3191 execution. Type jobs.new? for details.
3184
3192
3185 You can check the status of all jobs with jobs.status().
3193 You can check the status of all jobs with jobs.status().
3186
3194
3187 The jobs variable is set by IPython into the Python builtin namespace.
3195 The jobs variable is set by IPython into the Python builtin namespace.
3188 If you ever declare a variable named 'jobs', you will shadow this
3196 If you ever declare a variable named 'jobs', you will shadow this
3189 name. You can either delete your global jobs variable to regain
3197 name. You can either delete your global jobs variable to regain
3190 access to the job manager, or make a new name and assign it manually
3198 access to the job manager, or make a new name and assign it manually
3191 to the manager (stored in IPython's namespace). For example, to
3199 to the manager (stored in IPython's namespace). For example, to
3192 assign the job manager to the Jobs name, use:
3200 assign the job manager to the Jobs name, use:
3193
3201
3194 Jobs = __builtins__.jobs"""
3202 Jobs = __builtins__.jobs"""
3195
3203
3196 self.shell.jobs.new(parameter_s,self.shell.user_ns)
3204 self.shell.jobs.new(parameter_s,self.shell.user_ns)
3197
3205
3198 def magic_r(self, parameter_s=''):
3206 def magic_r(self, parameter_s=''):
3199 """Repeat previous input.
3207 """Repeat previous input.
3200
3208
3201 Note: Consider using the more powerfull %rep instead!
3209 Note: Consider using the more powerfull %rep instead!
3202
3210
3203 If given an argument, repeats the previous command which starts with
3211 If given an argument, repeats the previous command which starts with
3204 the same string, otherwise it just repeats the previous input.
3212 the same string, otherwise it just repeats the previous input.
3205
3213
3206 Shell escaped commands (with ! as first character) are not recognized
3214 Shell escaped commands (with ! as first character) are not recognized
3207 by this system, only pure python code and magic commands.
3215 by this system, only pure python code and magic commands.
3208 """
3216 """
3209
3217
3210 start = parameter_s.strip()
3218 start = parameter_s.strip()
3211 esc_magic = ESC_MAGIC
3219 esc_magic = ESC_MAGIC
3212 # Identify magic commands even if automagic is on (which means
3220 # Identify magic commands even if automagic is on (which means
3213 # the in-memory version is different from that typed by the user).
3221 # the in-memory version is different from that typed by the user).
3214 if self.shell.automagic:
3222 if self.shell.automagic:
3215 start_magic = esc_magic+start
3223 start_magic = esc_magic+start
3216 else:
3224 else:
3217 start_magic = start
3225 start_magic = start
3218 # Look through the input history in reverse
3226 # Look through the input history in reverse
3219 for n in range(len(self.shell.input_hist)-2,0,-1):
3227 for n in range(len(self.shell.input_hist)-2,0,-1):
3220 input = self.shell.input_hist[n]
3228 input = self.shell.input_hist[n]
3221 # skip plain 'r' lines so we don't recurse to infinity
3229 # skip plain 'r' lines so we don't recurse to infinity
3222 if input != '_ip.magic("r")\n' and \
3230 if input != '_ip.magic("r")\n' and \
3223 (input.startswith(start) or input.startswith(start_magic)):
3231 (input.startswith(start) or input.startswith(start_magic)):
3224 #print 'match',`input` # dbg
3232 #print 'match',`input` # dbg
3225 print 'Executing:',input,
3233 print 'Executing:',input,
3226 self.shell.runlines(input)
3234 self.shell.runlines(input)
3227 return
3235 return
3228 print 'No previous input matching `%s` found.' % start
3236 print 'No previous input matching `%s` found.' % start
3229
3237
3230
3238
3231 def magic_bookmark(self, parameter_s=''):
3239 def magic_bookmark(self, parameter_s=''):
3232 """Manage IPython's bookmark system.
3240 """Manage IPython's bookmark system.
3233
3241
3234 %bookmark <name> - set bookmark to current dir
3242 %bookmark <name> - set bookmark to current dir
3235 %bookmark <name> <dir> - set bookmark to <dir>
3243 %bookmark <name> <dir> - set bookmark to <dir>
3236 %bookmark -l - list all bookmarks
3244 %bookmark -l - list all bookmarks
3237 %bookmark -d <name> - remove bookmark
3245 %bookmark -d <name> - remove bookmark
3238 %bookmark -r - remove all bookmarks
3246 %bookmark -r - remove all bookmarks
3239
3247
3240 You can later on access a bookmarked folder with:
3248 You can later on access a bookmarked folder with:
3241 %cd -b <name>
3249 %cd -b <name>
3242 or simply '%cd <name>' if there is no directory called <name> AND
3250 or simply '%cd <name>' if there is no directory called <name> AND
3243 there is such a bookmark defined.
3251 there is such a bookmark defined.
3244
3252
3245 Your bookmarks persist through IPython sessions, but they are
3253 Your bookmarks persist through IPython sessions, but they are
3246 associated with each profile."""
3254 associated with each profile."""
3247
3255
3248 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3256 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3249 if len(args) > 2:
3257 if len(args) > 2:
3250 raise UsageError("%bookmark: too many arguments")
3258 raise UsageError("%bookmark: too many arguments")
3251
3259
3252 bkms = self.db.get('bookmarks',{})
3260 bkms = self.db.get('bookmarks',{})
3253
3261
3254 if opts.has_key('d'):
3262 if opts.has_key('d'):
3255 try:
3263 try:
3256 todel = args[0]
3264 todel = args[0]
3257 except IndexError:
3265 except IndexError:
3258 raise UsageError(
3266 raise UsageError(
3259 "%bookmark -d: must provide a bookmark to delete")
3267 "%bookmark -d: must provide a bookmark to delete")
3260 else:
3268 else:
3261 try:
3269 try:
3262 del bkms[todel]
3270 del bkms[todel]
3263 except KeyError:
3271 except KeyError:
3264 raise UsageError(
3272 raise UsageError(
3265 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3273 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3266
3274
3267 elif opts.has_key('r'):
3275 elif opts.has_key('r'):
3268 bkms = {}
3276 bkms = {}
3269 elif opts.has_key('l'):
3277 elif opts.has_key('l'):
3270 bks = bkms.keys()
3278 bks = bkms.keys()
3271 bks.sort()
3279 bks.sort()
3272 if bks:
3280 if bks:
3273 size = max(map(len,bks))
3281 size = max(map(len,bks))
3274 else:
3282 else:
3275 size = 0
3283 size = 0
3276 fmt = '%-'+str(size)+'s -> %s'
3284 fmt = '%-'+str(size)+'s -> %s'
3277 print 'Current bookmarks:'
3285 print 'Current bookmarks:'
3278 for bk in bks:
3286 for bk in bks:
3279 print fmt % (bk,bkms[bk])
3287 print fmt % (bk,bkms[bk])
3280 else:
3288 else:
3281 if not args:
3289 if not args:
3282 raise UsageError("%bookmark: You must specify the bookmark name")
3290 raise UsageError("%bookmark: You must specify the bookmark name")
3283 elif len(args)==1:
3291 elif len(args)==1:
3284 bkms[args[0]] = os.getcwd()
3292 bkms[args[0]] = os.getcwd()
3285 elif len(args)==2:
3293 elif len(args)==2:
3286 bkms[args[0]] = args[1]
3294 bkms[args[0]] = args[1]
3287 self.db['bookmarks'] = bkms
3295 self.db['bookmarks'] = bkms
3288
3296
3289 def magic_pycat(self, parameter_s=''):
3297 def magic_pycat(self, parameter_s=''):
3290 """Show a syntax-highlighted file through a pager.
3298 """Show a syntax-highlighted file through a pager.
3291
3299
3292 This magic is similar to the cat utility, but it will assume the file
3300 This magic is similar to the cat utility, but it will assume the file
3293 to be Python source and will show it with syntax highlighting. """
3301 to be Python source and will show it with syntax highlighting. """
3294
3302
3295 try:
3303 try:
3296 filename = get_py_filename(parameter_s)
3304 filename = get_py_filename(parameter_s)
3297 cont = file_read(filename)
3305 cont = file_read(filename)
3298 except IOError:
3306 except IOError:
3299 try:
3307 try:
3300 cont = eval(parameter_s,self.user_ns)
3308 cont = eval(parameter_s,self.user_ns)
3301 except NameError:
3309 except NameError:
3302 cont = None
3310 cont = None
3303 if cont is None:
3311 if cont is None:
3304 print "Error: no such file or variable"
3312 print "Error: no such file or variable"
3305 return
3313 return
3306
3314
3307 page(self.shell.pycolorize(cont),
3315 page(self.shell.pycolorize(cont),
3308 screen_lines=self.shell.usable_screen_length)
3316 screen_lines=self.shell.usable_screen_length)
3309
3317
3310 def _rerun_pasted(self):
3318 def _rerun_pasted(self):
3311 """ Rerun a previously pasted command.
3319 """ Rerun a previously pasted command.
3312 """
3320 """
3313 b = self.user_ns.get('pasted_block', None)
3321 b = self.user_ns.get('pasted_block', None)
3314 if b is None:
3322 if b is None:
3315 raise UsageError('No previous pasted block available')
3323 raise UsageError('No previous pasted block available')
3316 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3324 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3317 exec b in self.user_ns
3325 exec b in self.user_ns
3318
3326
3319 def _get_pasted_lines(self, sentinel):
3327 def _get_pasted_lines(self, sentinel):
3320 """ Yield pasted lines until the user enters the given sentinel value.
3328 """ Yield pasted lines until the user enters the given sentinel value.
3321 """
3329 """
3322 from IPython.core import iplib
3330 from IPython.core import iplib
3323 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3331 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3324 while True:
3332 while True:
3325 l = iplib.raw_input_original(':')
3333 l = iplib.raw_input_original(':')
3326 if l == sentinel:
3334 if l == sentinel:
3327 return
3335 return
3328 else:
3336 else:
3329 yield l
3337 yield l
3330
3338
3331 def _strip_pasted_lines_for_code(self, raw_lines):
3339 def _strip_pasted_lines_for_code(self, raw_lines):
3332 """ Strip non-code parts of a sequence of lines to return a block of
3340 """ Strip non-code parts of a sequence of lines to return a block of
3333 code.
3341 code.
3334 """
3342 """
3335 # Regular expressions that declare text we strip from the input:
3343 # Regular expressions that declare text we strip from the input:
3336 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3344 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3337 r'^\s*(\s?>)+', # Python input prompt
3345 r'^\s*(\s?>)+', # Python input prompt
3338 r'^\s*\.{3,}', # Continuation prompts
3346 r'^\s*\.{3,}', # Continuation prompts
3339 r'^\++',
3347 r'^\++',
3340 ]
3348 ]
3341
3349
3342 strip_from_start = map(re.compile,strip_re)
3350 strip_from_start = map(re.compile,strip_re)
3343
3351
3344 lines = []
3352 lines = []
3345 for l in raw_lines:
3353 for l in raw_lines:
3346 for pat in strip_from_start:
3354 for pat in strip_from_start:
3347 l = pat.sub('',l)
3355 l = pat.sub('',l)
3348 lines.append(l)
3356 lines.append(l)
3349
3357
3350 block = "\n".join(lines) + '\n'
3358 block = "\n".join(lines) + '\n'
3351 #print "block:\n",block
3359 #print "block:\n",block
3352 return block
3360 return block
3353
3361
3354 def _execute_block(self, block, par):
3362 def _execute_block(self, block, par):
3355 """ Execute a block, or store it in a variable, per the user's request.
3363 """ Execute a block, or store it in a variable, per the user's request.
3356 """
3364 """
3357 if not par:
3365 if not par:
3358 b = textwrap.dedent(block)
3366 b = textwrap.dedent(block)
3359 self.user_ns['pasted_block'] = b
3367 self.user_ns['pasted_block'] = b
3360 exec b in self.user_ns
3368 exec b in self.user_ns
3361 else:
3369 else:
3362 self.user_ns[par] = SList(block.splitlines())
3370 self.user_ns[par] = SList(block.splitlines())
3363 print "Block assigned to '%s'" % par
3371 print "Block assigned to '%s'" % par
3364
3372
3365 def magic_cpaste(self, parameter_s=''):
3373 def magic_cpaste(self, parameter_s=''):
3366 """Allows you to paste & execute a pre-formatted code block from clipboard.
3374 """Allows you to paste & execute a pre-formatted code block from clipboard.
3367
3375
3368 You must terminate the block with '--' (two minus-signs) alone on the
3376 You must terminate the block with '--' (two minus-signs) alone on the
3369 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3377 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3370 is the new sentinel for this operation)
3378 is the new sentinel for this operation)
3371
3379
3372 The block is dedented prior to execution to enable execution of method
3380 The block is dedented prior to execution to enable execution of method
3373 definitions. '>' and '+' characters at the beginning of a line are
3381 definitions. '>' and '+' characters at the beginning of a line are
3374 ignored, to allow pasting directly from e-mails, diff files and
3382 ignored, to allow pasting directly from e-mails, diff files and
3375 doctests (the '...' continuation prompt is also stripped). The
3383 doctests (the '...' continuation prompt is also stripped). The
3376 executed block is also assigned to variable named 'pasted_block' for
3384 executed block is also assigned to variable named 'pasted_block' for
3377 later editing with '%edit pasted_block'.
3385 later editing with '%edit pasted_block'.
3378
3386
3379 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3387 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3380 This assigns the pasted block to variable 'foo' as string, without
3388 This assigns the pasted block to variable 'foo' as string, without
3381 dedenting or executing it (preceding >>> and + is still stripped)
3389 dedenting or executing it (preceding >>> and + is still stripped)
3382
3390
3383 '%cpaste -r' re-executes the block previously entered by cpaste.
3391 '%cpaste -r' re-executes the block previously entered by cpaste.
3384
3392
3385 Do not be alarmed by garbled output on Windows (it's a readline bug).
3393 Do not be alarmed by garbled output on Windows (it's a readline bug).
3386 Just press enter and type -- (and press enter again) and the block
3394 Just press enter and type -- (and press enter again) and the block
3387 will be what was just pasted.
3395 will be what was just pasted.
3388
3396
3389 IPython statements (magics, shell escapes) are not supported (yet).
3397 IPython statements (magics, shell escapes) are not supported (yet).
3390
3398
3391 See also
3399 See also
3392 --------
3400 --------
3393 paste: automatically pull code from clipboard.
3401 paste: automatically pull code from clipboard.
3394 """
3402 """
3395
3403
3396 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
3404 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
3397 par = args.strip()
3405 par = args.strip()
3398 if opts.has_key('r'):
3406 if opts.has_key('r'):
3399 self._rerun_pasted()
3407 self._rerun_pasted()
3400 return
3408 return
3401
3409
3402 sentinel = opts.get('s','--')
3410 sentinel = opts.get('s','--')
3403
3411
3404 block = self._strip_pasted_lines_for_code(
3412 block = self._strip_pasted_lines_for_code(
3405 self._get_pasted_lines(sentinel))
3413 self._get_pasted_lines(sentinel))
3406
3414
3407 self._execute_block(block, par)
3415 self._execute_block(block, par)
3408
3416
3409 def magic_paste(self, parameter_s=''):
3417 def magic_paste(self, parameter_s=''):
3410 """Allows you to paste & execute a pre-formatted code block from clipboard.
3418 """Allows you to paste & execute a pre-formatted code block from clipboard.
3411
3419
3412 The text is pulled directly from the clipboard without user
3420 The text is pulled directly from the clipboard without user
3413 intervention and printed back on the screen before execution (unless
3421 intervention and printed back on the screen before execution (unless
3414 the -q flag is given to force quiet mode).
3422 the -q flag is given to force quiet mode).
3415
3423
3416 The block is dedented prior to execution to enable execution of method
3424 The block is dedented prior to execution to enable execution of method
3417 definitions. '>' and '+' characters at the beginning of a line are
3425 definitions. '>' and '+' characters at the beginning of a line are
3418 ignored, to allow pasting directly from e-mails, diff files and
3426 ignored, to allow pasting directly from e-mails, diff files and
3419 doctests (the '...' continuation prompt is also stripped). The
3427 doctests (the '...' continuation prompt is also stripped). The
3420 executed block is also assigned to variable named 'pasted_block' for
3428 executed block is also assigned to variable named 'pasted_block' for
3421 later editing with '%edit pasted_block'.
3429 later editing with '%edit pasted_block'.
3422
3430
3423 You can also pass a variable name as an argument, e.g. '%paste foo'.
3431 You can also pass a variable name as an argument, e.g. '%paste foo'.
3424 This assigns the pasted block to variable 'foo' as string, without
3432 This assigns the pasted block to variable 'foo' as string, without
3425 dedenting or executing it (preceding >>> and + is still stripped)
3433 dedenting or executing it (preceding >>> and + is still stripped)
3426
3434
3427 Options
3435 Options
3428 -------
3436 -------
3429
3437
3430 -r: re-executes the block previously entered by cpaste.
3438 -r: re-executes the block previously entered by cpaste.
3431
3439
3432 -q: quiet mode: do not echo the pasted text back to the terminal.
3440 -q: quiet mode: do not echo the pasted text back to the terminal.
3433
3441
3434 IPython statements (magics, shell escapes) are not supported (yet).
3442 IPython statements (magics, shell escapes) are not supported (yet).
3435
3443
3436 See also
3444 See also
3437 --------
3445 --------
3438 cpaste: manually paste code into terminal until you mark its end.
3446 cpaste: manually paste code into terminal until you mark its end.
3439 """
3447 """
3440 opts,args = self.parse_options(parameter_s,'rq',mode='string')
3448 opts,args = self.parse_options(parameter_s,'rq',mode='string')
3441 par = args.strip()
3449 par = args.strip()
3442 if opts.has_key('r'):
3450 if opts.has_key('r'):
3443 self._rerun_pasted()
3451 self._rerun_pasted()
3444 return
3452 return
3445
3453
3446 text = self.shell.hooks.clipboard_get()
3454 text = self.shell.hooks.clipboard_get()
3447 block = self._strip_pasted_lines_for_code(text.splitlines())
3455 block = self._strip_pasted_lines_for_code(text.splitlines())
3448
3456
3449 # By default, echo back to terminal unless quiet mode is requested
3457 # By default, echo back to terminal unless quiet mode is requested
3450 if not opts.has_key('q'):
3458 if not opts.has_key('q'):
3451 write = self.shell.write
3459 write = self.shell.write
3452 write(self.shell.pycolorize(block))
3460 write(self.shell.pycolorize(block))
3453 if not block.endswith('\n'):
3461 if not block.endswith('\n'):
3454 write('\n')
3462 write('\n')
3455 write("## -- End pasted text --\n")
3463 write("## -- End pasted text --\n")
3456
3464
3457 self._execute_block(block, par)
3465 self._execute_block(block, par)
3458
3466
3459 def magic_quickref(self,arg):
3467 def magic_quickref(self,arg):
3460 """ Show a quick reference sheet """
3468 """ Show a quick reference sheet """
3461 import IPython.core.usage
3469 import IPython.core.usage
3462 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3470 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3463
3471
3464 page(qr)
3472 page(qr)
3465
3473
3466 def magic_doctest_mode(self,parameter_s=''):
3474 def magic_doctest_mode(self,parameter_s=''):
3467 """Toggle doctest mode on and off.
3475 """Toggle doctest mode on and off.
3468
3476
3469 This mode allows you to toggle the prompt behavior between normal
3477 This mode allows you to toggle the prompt behavior between normal
3470 IPython prompts and ones that are as similar to the default IPython
3478 IPython prompts and ones that are as similar to the default IPython
3471 interpreter as possible.
3479 interpreter as possible.
3472
3480
3473 It also supports the pasting of code snippets that have leading '>>>'
3481 It also supports the pasting of code snippets that have leading '>>>'
3474 and '...' prompts in them. This means that you can paste doctests from
3482 and '...' prompts in them. This means that you can paste doctests from
3475 files or docstrings (even if they have leading whitespace), and the
3483 files or docstrings (even if they have leading whitespace), and the
3476 code will execute correctly. You can then use '%history -tn' to see
3484 code will execute correctly. You can then use '%history -tn' to see
3477 the translated history without line numbers; this will give you the
3485 the translated history without line numbers; this will give you the
3478 input after removal of all the leading prompts and whitespace, which
3486 input after removal of all the leading prompts and whitespace, which
3479 can be pasted back into an editor.
3487 can be pasted back into an editor.
3480
3488
3481 With these features, you can switch into this mode easily whenever you
3489 With these features, you can switch into this mode easily whenever you
3482 need to do testing and changes to doctests, without having to leave
3490 need to do testing and changes to doctests, without having to leave
3483 your existing IPython session.
3491 your existing IPython session.
3484 """
3492 """
3485
3493
3486 from IPython.utils.ipstruct import Struct
3494 from IPython.utils.ipstruct import Struct
3487
3495
3488 # Shorthands
3496 # Shorthands
3489 shell = self.shell
3497 shell = self.shell
3490 oc = shell.outputcache
3498 oc = shell.outputcache
3491 meta = shell.meta
3499 meta = shell.meta
3492 # dstore is a data store kept in the instance metadata bag to track any
3500 # dstore is a data store kept in the instance metadata bag to track any
3493 # changes we make, so we can undo them later.
3501 # changes we make, so we can undo them later.
3494 dstore = meta.setdefault('doctest_mode',Struct())
3502 dstore = meta.setdefault('doctest_mode',Struct())
3495 save_dstore = dstore.setdefault
3503 save_dstore = dstore.setdefault
3496
3504
3497 # save a few values we'll need to recover later
3505 # save a few values we'll need to recover later
3498 mode = save_dstore('mode',False)
3506 mode = save_dstore('mode',False)
3499 save_dstore('rc_pprint',shell.pprint)
3507 save_dstore('rc_pprint',shell.pprint)
3500 save_dstore('xmode',shell.InteractiveTB.mode)
3508 save_dstore('xmode',shell.InteractiveTB.mode)
3501 save_dstore('rc_separate_out',shell.separate_out)
3509 save_dstore('rc_separate_out',shell.separate_out)
3502 save_dstore('rc_separate_out2',shell.separate_out2)
3510 save_dstore('rc_separate_out2',shell.separate_out2)
3503 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3511 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3504 save_dstore('rc_separate_in',shell.separate_in)
3512 save_dstore('rc_separate_in',shell.separate_in)
3505
3513
3506 if mode == False:
3514 if mode == False:
3507 # turn on
3515 # turn on
3508 oc.prompt1.p_template = '>>> '
3516 oc.prompt1.p_template = '>>> '
3509 oc.prompt2.p_template = '... '
3517 oc.prompt2.p_template = '... '
3510 oc.prompt_out.p_template = ''
3518 oc.prompt_out.p_template = ''
3511
3519
3512 # Prompt separators like plain python
3520 # Prompt separators like plain python
3513 oc.input_sep = oc.prompt1.sep = ''
3521 oc.input_sep = oc.prompt1.sep = ''
3514 oc.output_sep = ''
3522 oc.output_sep = ''
3515 oc.output_sep2 = ''
3523 oc.output_sep2 = ''
3516
3524
3517 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3525 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3518 oc.prompt_out.pad_left = False
3526 oc.prompt_out.pad_left = False
3519
3527
3520 shell.pprint = False
3528 shell.pprint = False
3521
3529
3522 shell.magic_xmode('Plain')
3530 shell.magic_xmode('Plain')
3523
3531
3524 else:
3532 else:
3525 # turn off
3533 # turn off
3526 oc.prompt1.p_template = shell.prompt_in1
3534 oc.prompt1.p_template = shell.prompt_in1
3527 oc.prompt2.p_template = shell.prompt_in2
3535 oc.prompt2.p_template = shell.prompt_in2
3528 oc.prompt_out.p_template = shell.prompt_out
3536 oc.prompt_out.p_template = shell.prompt_out
3529
3537
3530 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3538 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3531
3539
3532 oc.output_sep = dstore.rc_separate_out
3540 oc.output_sep = dstore.rc_separate_out
3533 oc.output_sep2 = dstore.rc_separate_out2
3541 oc.output_sep2 = dstore.rc_separate_out2
3534
3542
3535 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3543 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3536 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3544 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3537
3545
3538 shell.pprint = dstore.rc_pprint
3546 shell.pprint = dstore.rc_pprint
3539
3547
3540 shell.magic_xmode(dstore.xmode)
3548 shell.magic_xmode(dstore.xmode)
3541
3549
3542 # Store new mode and inform
3550 # Store new mode and inform
3543 dstore.mode = bool(1-int(mode))
3551 dstore.mode = bool(1-int(mode))
3544 print 'Doctest mode is:',
3552 print 'Doctest mode is:',
3545 print ['OFF','ON'][dstore.mode]
3553 print ['OFF','ON'][dstore.mode]
3546
3554
3547 def magic_gui(self, parameter_s=''):
3555 def magic_gui(self, parameter_s=''):
3548 """Enable or disable IPython GUI event loop integration.
3556 """Enable or disable IPython GUI event loop integration.
3549
3557
3550 %gui [-a] [GUINAME]
3558 %gui [-a] [GUINAME]
3551
3559
3552 This magic replaces IPython's threaded shells that were activated
3560 This magic replaces IPython's threaded shells that were activated
3553 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3561 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3554 can now be enabled, disabled and swtiched at runtime and keyboard
3562 can now be enabled, disabled and swtiched at runtime and keyboard
3555 interrupts should work without any problems. The following toolkits
3563 interrupts should work without any problems. The following toolkits
3556 are supported: wxPython, PyQt4, PyGTK, and Tk::
3564 are supported: wxPython, PyQt4, PyGTK, and Tk::
3557
3565
3558 %gui wx # enable wxPython event loop integration
3566 %gui wx # enable wxPython event loop integration
3559 %gui qt4|qt # enable PyQt4 event loop integration
3567 %gui qt4|qt # enable PyQt4 event loop integration
3560 %gui gtk # enable PyGTK event loop integration
3568 %gui gtk # enable PyGTK event loop integration
3561 %gui tk # enable Tk event loop integration
3569 %gui tk # enable Tk event loop integration
3562 %gui # disable all event loop integration
3570 %gui # disable all event loop integration
3563
3571
3564 WARNING: after any of these has been called you can simply create
3572 WARNING: after any of these has been called you can simply create
3565 an application object, but DO NOT start the event loop yourself, as
3573 an application object, but DO NOT start the event loop yourself, as
3566 we have already handled that.
3574 we have already handled that.
3567
3575
3568 If you want us to create an appropriate application object add the
3576 If you want us to create an appropriate application object add the
3569 "-a" flag to your command::
3577 "-a" flag to your command::
3570
3578
3571 %gui -a wx
3579 %gui -a wx
3572
3580
3573 This is highly recommended for most users.
3581 This is highly recommended for most users.
3574 """
3582 """
3575 opts, arg = self.parse_options(parameter_s,'a')
3583 opts, arg = self.parse_options(parameter_s,'a')
3576 if arg=='': arg = None
3584 if arg=='': arg = None
3577 return enable_gui(arg, 'a' in opts)
3585 return enable_gui(arg, 'a' in opts)
3578
3586
3579 def magic_load_ext(self, module_str):
3587 def magic_load_ext(self, module_str):
3580 """Load an IPython extension by its module name."""
3588 """Load an IPython extension by its module name."""
3581 return self.load_extension(module_str)
3589 return self.load_extension(module_str)
3582
3590
3583 def magic_unload_ext(self, module_str):
3591 def magic_unload_ext(self, module_str):
3584 """Unload an IPython extension by its module name."""
3592 """Unload an IPython extension by its module name."""
3585 self.unload_extension(module_str)
3593 self.unload_extension(module_str)
3586
3594
3587 def magic_reload_ext(self, module_str):
3595 def magic_reload_ext(self, module_str):
3588 """Reload an IPython extension by its module name."""
3596 """Reload an IPython extension by its module name."""
3589 self.reload_extension(module_str)
3597 self.reload_extension(module_str)
3590
3598
3591 @testdec.skip_doctest
3599 @testdec.skip_doctest
3592 def magic_install_profiles(self, s):
3600 def magic_install_profiles(self, s):
3593 """Install the default IPython profiles into the .ipython dir.
3601 """Install the default IPython profiles into the .ipython dir.
3594
3602
3595 If the default profiles have already been installed, they will not
3603 If the default profiles have already been installed, they will not
3596 be overwritten. You can force overwriting them by using the ``-o``
3604 be overwritten. You can force overwriting them by using the ``-o``
3597 option::
3605 option::
3598
3606
3599 In [1]: %install_profiles -o
3607 In [1]: %install_profiles -o
3600 """
3608 """
3601 if '-o' in s:
3609 if '-o' in s:
3602 overwrite = True
3610 overwrite = True
3603 else:
3611 else:
3604 overwrite = False
3612 overwrite = False
3605 from IPython.config import profile
3613 from IPython.config import profile
3606 profile_dir = os.path.split(profile.__file__)[0]
3614 profile_dir = os.path.split(profile.__file__)[0]
3607 ipython_dir = self.ipython_dir
3615 ipython_dir = self.ipython_dir
3608 files = os.listdir(profile_dir)
3616 files = os.listdir(profile_dir)
3609
3617
3610 to_install = []
3618 to_install = []
3611 for f in files:
3619 for f in files:
3612 if f.startswith('ipython_config'):
3620 if f.startswith('ipython_config'):
3613 src = os.path.join(profile_dir, f)
3621 src = os.path.join(profile_dir, f)
3614 dst = os.path.join(ipython_dir, f)
3622 dst = os.path.join(ipython_dir, f)
3615 if (not os.path.isfile(dst)) or overwrite:
3623 if (not os.path.isfile(dst)) or overwrite:
3616 to_install.append((f, src, dst))
3624 to_install.append((f, src, dst))
3617 if len(to_install)>0:
3625 if len(to_install)>0:
3618 print "Installing profiles to: ", ipython_dir
3626 print "Installing profiles to: ", ipython_dir
3619 for (f, src, dst) in to_install:
3627 for (f, src, dst) in to_install:
3620 shutil.copy(src, dst)
3628 shutil.copy(src, dst)
3621 print " %s" % f
3629 print " %s" % f
3622
3630
3623 def magic_install_default_config(self, s):
3631 def magic_install_default_config(self, s):
3624 """Install IPython's default config file into the .ipython dir.
3632 """Install IPython's default config file into the .ipython dir.
3625
3633
3626 If the default config file (:file:`ipython_config.py`) is already
3634 If the default config file (:file:`ipython_config.py`) is already
3627 installed, it will not be overwritten. You can force overwriting
3635 installed, it will not be overwritten. You can force overwriting
3628 by using the ``-o`` option::
3636 by using the ``-o`` option::
3629
3637
3630 In [1]: %install_default_config
3638 In [1]: %install_default_config
3631 """
3639 """
3632 if '-o' in s:
3640 if '-o' in s:
3633 overwrite = True
3641 overwrite = True
3634 else:
3642 else:
3635 overwrite = False
3643 overwrite = False
3636 from IPython.config import default
3644 from IPython.config import default
3637 config_dir = os.path.split(default.__file__)[0]
3645 config_dir = os.path.split(default.__file__)[0]
3638 ipython_dir = self.ipython_dir
3646 ipython_dir = self.ipython_dir
3639 default_config_file_name = 'ipython_config.py'
3647 default_config_file_name = 'ipython_config.py'
3640 src = os.path.join(config_dir, default_config_file_name)
3648 src = os.path.join(config_dir, default_config_file_name)
3641 dst = os.path.join(ipython_dir, default_config_file_name)
3649 dst = os.path.join(ipython_dir, default_config_file_name)
3642 if (not os.path.isfile(dst)) or overwrite:
3650 if (not os.path.isfile(dst)) or overwrite:
3643 shutil.copy(src, dst)
3651 shutil.copy(src, dst)
3644 print "Installing default config file: %s" % dst
3652 print "Installing default config file: %s" % dst
3645
3653
3646 # Pylab support: simple wrappers that activate pylab, load gui input
3654 # Pylab support: simple wrappers that activate pylab, load gui input
3647 # handling and modify slightly %run
3655 # handling and modify slightly %run
3648
3656
3649 @testdec.skip_doctest
3657 @testdec.skip_doctest
3650 def _pylab_magic_run(self, parameter_s=''):
3658 def _pylab_magic_run(self, parameter_s=''):
3651 Magic.magic_run(self, parameter_s,
3659 Magic.magic_run(self, parameter_s,
3652 runner=mpl_runner(self.shell.safe_execfile))
3660 runner=mpl_runner(self.shell.safe_execfile))
3653
3661
3654 _pylab_magic_run.__doc__ = magic_run.__doc__
3662 _pylab_magic_run.__doc__ = magic_run.__doc__
3655
3663
3656 @testdec.skip_doctest
3664 @testdec.skip_doctest
3657 def magic_pylab(self, s):
3665 def magic_pylab(self, s):
3658 """Load numpy and matplotlib to work interactively.
3666 """Load numpy and matplotlib to work interactively.
3659
3667
3660 %pylab [GUINAME]
3668 %pylab [GUINAME]
3661
3669
3662 This function lets you activate pylab (matplotlib, numpy and
3670 This function lets you activate pylab (matplotlib, numpy and
3663 interactive support) at any point during an IPython session.
3671 interactive support) at any point during an IPython session.
3664
3672
3665 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3673 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3666 pylab and mlab, as well as all names from numpy and pylab.
3674 pylab and mlab, as well as all names from numpy and pylab.
3667
3675
3668 Parameters
3676 Parameters
3669 ----------
3677 ----------
3670 guiname : optional
3678 guiname : optional
3671 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or
3679 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or
3672 'tk'). If given, the corresponding Matplotlib backend is used,
3680 'tk'). If given, the corresponding Matplotlib backend is used,
3673 otherwise matplotlib's default (which you can override in your
3681 otherwise matplotlib's default (which you can override in your
3674 matplotlib config file) is used.
3682 matplotlib config file) is used.
3675
3683
3676 Examples
3684 Examples
3677 --------
3685 --------
3678 In this case, where the MPL default is TkAgg:
3686 In this case, where the MPL default is TkAgg:
3679 In [2]: %pylab
3687 In [2]: %pylab
3680
3688
3681 Welcome to pylab, a matplotlib-based Python environment.
3689 Welcome to pylab, a matplotlib-based Python environment.
3682 Backend in use: TkAgg
3690 Backend in use: TkAgg
3683 For more information, type 'help(pylab)'.
3691 For more information, type 'help(pylab)'.
3684
3692
3685 But you can explicitly request a different backend:
3693 But you can explicitly request a different backend:
3686 In [3]: %pylab qt
3694 In [3]: %pylab qt
3687
3695
3688 Welcome to pylab, a matplotlib-based Python environment.
3696 Welcome to pylab, a matplotlib-based Python environment.
3689 Backend in use: Qt4Agg
3697 Backend in use: Qt4Agg
3690 For more information, type 'help(pylab)'.
3698 For more information, type 'help(pylab)'.
3691 """
3699 """
3692 self.shell.enable_pylab(s)
3700 self.shell.enable_pylab(s)
3693
3701
3694 def magic_tb(self, s):
3702 def magic_tb(self, s):
3695 """Print the last traceback with the currently active exception mode.
3703 """Print the last traceback with the currently active exception mode.
3696
3704
3697 See %xmode for changing exception reporting modes."""
3705 See %xmode for changing exception reporting modes."""
3698 self.shell.showtraceback()
3706 self.shell.showtraceback()
3699
3707
3700 # end Magic
3708 # end Magic
@@ -1,1051 +1,1050 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 Prefiltering components.
4 Prefiltering components.
5
5
6 Prefilters transform user input before it is exec'd by Python. These
6 Prefilters transform user input before it is exec'd by Python. These
7 transforms are used to implement additional syntax such as !ls and %magic.
7 transforms are used to implement additional syntax such as !ls and %magic.
8
8
9 Authors:
9 Authors:
10
10
11 * Brian Granger
11 * Brian Granger
12 * Fernando Perez
12 * Fernando Perez
13 * Dan Milstein
13 * Dan Milstein
14 * Ville Vainio
14 * Ville Vainio
15 """
15 """
16
16
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18 # Copyright (C) 2008-2009 The IPython Development Team
18 # Copyright (C) 2008-2009 The IPython Development Team
19 #
19 #
20 # Distributed under the terms of the BSD License. The full license is in
20 # Distributed under the terms of the BSD License. The full license is in
21 # the file COPYING, distributed as part of this software.
21 # the file COPYING, distributed as part of this software.
22 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
23
23
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25 # Imports
25 # Imports
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27
27
28 import __builtin__
28 import __builtin__
29 import codeop
29 import codeop
30 import re
30 import re
31
31
32 from IPython.core.alias import AliasManager
32 from IPython.core.alias import AliasManager
33 from IPython.core.autocall import IPyAutocall
33 from IPython.core.autocall import IPyAutocall
34 from IPython.core.component import Component
34 from IPython.core.component import Component
35 from IPython.core.splitinput import split_user_input
35 from IPython.core.splitinput import split_user_input
36 from IPython.core.page import page
36 from IPython.core.page import page
37
37
38 from IPython.utils.traitlets import List, Int, Any, Str, CBool, Bool
38 from IPython.utils.traitlets import List, Int, Any, Str, CBool, Bool
39 from IPython.utils.io import Term
39 from IPython.utils.io import Term
40 from IPython.utils.text import make_quoted_expr
40 from IPython.utils.text import make_quoted_expr
41 from IPython.utils.autoattr import auto_attr
41 from IPython.utils.autoattr import auto_attr
42
42
43 #-----------------------------------------------------------------------------
43 #-----------------------------------------------------------------------------
44 # Global utilities, errors and constants
44 # Global utilities, errors and constants
45 #-----------------------------------------------------------------------------
45 #-----------------------------------------------------------------------------
46
46
47 # Warning, these cannot be changed unless various regular expressions
47 # Warning, these cannot be changed unless various regular expressions
48 # are updated in a number of places. Not great, but at least we told you.
48 # are updated in a number of places. Not great, but at least we told you.
49 ESC_SHELL = '!'
49 ESC_SHELL = '!'
50 ESC_SH_CAP = '!!'
50 ESC_SH_CAP = '!!'
51 ESC_HELP = '?'
51 ESC_HELP = '?'
52 ESC_MAGIC = '%'
52 ESC_MAGIC = '%'
53 ESC_QUOTE = ','
53 ESC_QUOTE = ','
54 ESC_QUOTE2 = ';'
54 ESC_QUOTE2 = ';'
55 ESC_PAREN = '/'
55 ESC_PAREN = '/'
56
56
57
57
58 class PrefilterError(Exception):
58 class PrefilterError(Exception):
59 pass
59 pass
60
60
61
61
62 # RegExp to identify potential function names
62 # RegExp to identify potential function names
63 re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
63 re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
64
64
65 # RegExp to exclude strings with this start from autocalling. In
65 # RegExp to exclude strings with this start from autocalling. In
66 # particular, all binary operators should be excluded, so that if foo is
66 # particular, all binary operators should be excluded, so that if foo is
67 # callable, foo OP bar doesn't become foo(OP bar), which is invalid. The
67 # callable, foo OP bar doesn't become foo(OP bar), which is invalid. The
68 # characters '!=()' don't need to be checked for, as the checkPythonChars
68 # characters '!=()' don't need to be checked for, as the checkPythonChars
69 # routine explicitely does so, to catch direct calls and rebindings of
69 # routine explicitely does so, to catch direct calls and rebindings of
70 # existing names.
70 # existing names.
71
71
72 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
72 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
73 # it affects the rest of the group in square brackets.
73 # it affects the rest of the group in square brackets.
74 re_exclude_auto = re.compile(r'^[,&^\|\*/\+-]'
74 re_exclude_auto = re.compile(r'^[,&^\|\*/\+-]'
75 r'|^is |^not |^in |^and |^or ')
75 r'|^is |^not |^in |^and |^or ')
76
76
77 # try to catch also methods for stuff in lists/tuples/dicts: off
77 # try to catch also methods for stuff in lists/tuples/dicts: off
78 # (experimental). For this to work, the line_split regexp would need
78 # (experimental). For this to work, the line_split regexp would need
79 # to be modified so it wouldn't break things at '['. That line is
79 # to be modified so it wouldn't break things at '['. That line is
80 # nasty enough that I shouldn't change it until I can test it _well_.
80 # nasty enough that I shouldn't change it until I can test it _well_.
81 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
81 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
82
82
83
83
84 # Handler Check Utilities
84 # Handler Check Utilities
85 def is_shadowed(identifier, ip):
85 def is_shadowed(identifier, ip):
86 """Is the given identifier defined in one of the namespaces which shadow
86 """Is the given identifier defined in one of the namespaces which shadow
87 the alias and magic namespaces? Note that an identifier is different
87 the alias and magic namespaces? Note that an identifier is different
88 than ifun, because it can not contain a '.' character."""
88 than ifun, because it can not contain a '.' character."""
89 # This is much safer than calling ofind, which can change state
89 # This is much safer than calling ofind, which can change state
90 return (identifier in ip.user_ns \
90 return (identifier in ip.user_ns \
91 or identifier in ip.internal_ns \
91 or identifier in ip.internal_ns \
92 or identifier in ip.ns_table['builtin'])
92 or identifier in ip.ns_table['builtin'])
93
93
94
94
95 #-----------------------------------------------------------------------------
95 #-----------------------------------------------------------------------------
96 # The LineInfo class used throughout
96 # The LineInfo class used throughout
97 #-----------------------------------------------------------------------------
97 #-----------------------------------------------------------------------------
98
98
99
99
100 class LineInfo(object):
100 class LineInfo(object):
101 """A single line of input and associated info.
101 """A single line of input and associated info.
102
102
103 Includes the following as properties:
103 Includes the following as properties:
104
104
105 line
105 line
106 The original, raw line
106 The original, raw line
107
107
108 continue_prompt
108 continue_prompt
109 Is this line a continuation in a sequence of multiline input?
109 Is this line a continuation in a sequence of multiline input?
110
110
111 pre
111 pre
112 The initial esc character or whitespace.
112 The initial esc character or whitespace.
113
113
114 pre_char
114 pre_char
115 The escape character(s) in pre or the empty string if there isn't one.
115 The escape character(s) in pre or the empty string if there isn't one.
116 Note that '!!' is a possible value for pre_char. Otherwise it will
116 Note that '!!' is a possible value for pre_char. Otherwise it will
117 always be a single character.
117 always be a single character.
118
118
119 pre_whitespace
119 pre_whitespace
120 The leading whitespace from pre if it exists. If there is a pre_char,
120 The leading whitespace from pre if it exists. If there is a pre_char,
121 this is just ''.
121 this is just ''.
122
122
123 ifun
123 ifun
124 The 'function part', which is basically the maximal initial sequence
124 The 'function part', which is basically the maximal initial sequence
125 of valid python identifiers and the '.' character. This is what is
125 of valid python identifiers and the '.' character. This is what is
126 checked for alias and magic transformations, used for auto-calling,
126 checked for alias and magic transformations, used for auto-calling,
127 etc.
127 etc.
128
128
129 the_rest
129 the_rest
130 Everything else on the line.
130 Everything else on the line.
131 """
131 """
132 def __init__(self, line, continue_prompt):
132 def __init__(self, line, continue_prompt):
133 self.line = line
133 self.line = line
134 self.continue_prompt = continue_prompt
134 self.continue_prompt = continue_prompt
135 self.pre, self.ifun, self.the_rest = split_user_input(line)
135 self.pre, self.ifun, self.the_rest = split_user_input(line)
136
136
137 self.pre_char = self.pre.strip()
137 self.pre_char = self.pre.strip()
138 if self.pre_char:
138 if self.pre_char:
139 self.pre_whitespace = '' # No whitespace allowd before esc chars
139 self.pre_whitespace = '' # No whitespace allowd before esc chars
140 else:
140 else:
141 self.pre_whitespace = self.pre
141 self.pre_whitespace = self.pre
142
142
143 self._oinfo = None
143 self._oinfo = None
144
144
145 def ofind(self, ip):
145 def ofind(self, ip):
146 """Do a full, attribute-walking lookup of the ifun in the various
146 """Do a full, attribute-walking lookup of the ifun in the various
147 namespaces for the given IPython InteractiveShell instance.
147 namespaces for the given IPython InteractiveShell instance.
148
148
149 Return a dict with keys: found,obj,ospace,ismagic
149 Return a dict with keys: found,obj,ospace,ismagic
150
150
151 Note: can cause state changes because of calling getattr, but should
151 Note: can cause state changes because of calling getattr, but should
152 only be run if autocall is on and if the line hasn't matched any
152 only be run if autocall is on and if the line hasn't matched any
153 other, less dangerous handlers.
153 other, less dangerous handlers.
154
154
155 Does cache the results of the call, so can be called multiple times
155 Does cache the results of the call, so can be called multiple times
156 without worrying about *further* damaging state.
156 without worrying about *further* damaging state.
157 """
157 """
158 if not self._oinfo:
158 if not self._oinfo:
159 # ip.shell._ofind is actually on the Magic class!
159 # ip.shell._ofind is actually on the Magic class!
160 self._oinfo = ip.shell._ofind(self.ifun)
160 self._oinfo = ip.shell._ofind(self.ifun)
161 return self._oinfo
161 return self._oinfo
162
162
163 def __str__(self):
163 def __str__(self):
164 return "Lineinfo [%s|%s|%s]" %(self.pre, self.ifun, self.the_rest)
164 return "Lineinfo [%s|%s|%s]" %(self.pre, self.ifun, self.the_rest)
165
165
166
166
167 #-----------------------------------------------------------------------------
167 #-----------------------------------------------------------------------------
168 # Main Prefilter manager
168 # Main Prefilter manager
169 #-----------------------------------------------------------------------------
169 #-----------------------------------------------------------------------------
170
170
171
171
172 class PrefilterManager(Component):
172 class PrefilterManager(Component):
173 """Main prefilter component.
173 """Main prefilter component.
174
174
175 The IPython prefilter is run on all user input before it is run. The
175 The IPython prefilter is run on all user input before it is run. The
176 prefilter consumes lines of input and produces transformed lines of
176 prefilter consumes lines of input and produces transformed lines of
177 input.
177 input.
178
178
179 The iplementation consists of two phases:
179 The iplementation consists of two phases:
180
180
181 1. Transformers
181 1. Transformers
182 2. Checkers and handlers
182 2. Checkers and handlers
183
183
184 Over time, we plan on deprecating the checkers and handlers and doing
184 Over time, we plan on deprecating the checkers and handlers and doing
185 everything in the transformers.
185 everything in the transformers.
186
186
187 The transformers are instances of :class:`PrefilterTransformer` and have
187 The transformers are instances of :class:`PrefilterTransformer` and have
188 a single method :meth:`transform` that takes a line and returns a
188 a single method :meth:`transform` that takes a line and returns a
189 transformed line. The transformation can be accomplished using any
189 transformed line. The transformation can be accomplished using any
190 tool, but our current ones use regular expressions for speed. We also
190 tool, but our current ones use regular expressions for speed. We also
191 ship :mod:`pyparsing` in :mod:`IPython.external` for use in transformers.
191 ship :mod:`pyparsing` in :mod:`IPython.external` for use in transformers.
192
192
193 After all the transformers have been run, the line is fed to the checkers,
193 After all the transformers have been run, the line is fed to the checkers,
194 which are instances of :class:`PrefilterChecker`. The line is passed to
194 which are instances of :class:`PrefilterChecker`. The line is passed to
195 the :meth:`check` method, which either returns `None` or a
195 the :meth:`check` method, which either returns `None` or a
196 :class:`PrefilterHandler` instance. If `None` is returned, the other
196 :class:`PrefilterHandler` instance. If `None` is returned, the other
197 checkers are tried. If an :class:`PrefilterHandler` instance is returned,
197 checkers are tried. If an :class:`PrefilterHandler` instance is returned,
198 the line is passed to the :meth:`handle` method of the returned
198 the line is passed to the :meth:`handle` method of the returned
199 handler and no further checkers are tried.
199 handler and no further checkers are tried.
200
200
201 Both transformers and checkers have a `priority` attribute, that determines
201 Both transformers and checkers have a `priority` attribute, that determines
202 the order in which they are called. Smaller priorities are tried first.
202 the order in which they are called. Smaller priorities are tried first.
203
203
204 Both transformers and checkers also have `enabled` attribute, which is
204 Both transformers and checkers also have `enabled` attribute, which is
205 a boolean that determines if the instance is used.
205 a boolean that determines if the instance is used.
206
206
207 Users or developers can change the priority or enabled attribute of
207 Users or developers can change the priority or enabled attribute of
208 transformers or checkers, but they must call the :meth:`sort_checkers`
208 transformers or checkers, but they must call the :meth:`sort_checkers`
209 or :meth:`sort_transformers` method after changing the priority.
209 or :meth:`sort_transformers` method after changing the priority.
210 """
210 """
211
211
212 multi_line_specials = CBool(True, config=True)
212 multi_line_specials = CBool(True, config=True)
213
213
214 def __init__(self, parent, config=None):
214 def __init__(self, parent, config=None):
215 super(PrefilterManager, self).__init__(parent, config=config)
215 super(PrefilterManager, self).__init__(parent, config=config)
216 self.init_transformers()
216 self.init_transformers()
217 self.init_handlers()
217 self.init_handlers()
218 self.init_checkers()
218 self.init_checkers()
219
219
220 @auto_attr
220 @auto_attr
221 def shell(self):
221 def shell(self):
222 return Component.get_instances(
222 return Component.get_instances(
223 root=self.root,
223 root=self.root,
224 klass='IPython.core.iplib.InteractiveShell')[0]
224 klass='IPython.core.iplib.InteractiveShell')[0]
225
225
226 #-------------------------------------------------------------------------
226 #-------------------------------------------------------------------------
227 # API for managing transformers
227 # API for managing transformers
228 #-------------------------------------------------------------------------
228 #-------------------------------------------------------------------------
229
229
230 def init_transformers(self):
230 def init_transformers(self):
231 """Create the default transformers."""
231 """Create the default transformers."""
232 self._transformers = []
232 self._transformers = []
233 for transformer_cls in _default_transformers:
233 for transformer_cls in _default_transformers:
234 transformer_cls(self, config=self.config)
234 transformer_cls(self, config=self.config)
235
235
236 def sort_transformers(self):
236 def sort_transformers(self):
237 """Sort the transformers by priority.
237 """Sort the transformers by priority.
238
238
239 This must be called after the priority of a transformer is changed.
239 This must be called after the priority of a transformer is changed.
240 The :meth:`register_transformer` method calls this automatically.
240 The :meth:`register_transformer` method calls this automatically.
241 """
241 """
242 self._transformers.sort(cmp=lambda x,y: x.priority-y.priority)
242 self._transformers.sort(cmp=lambda x,y: x.priority-y.priority)
243
243
244 @property
244 @property
245 def transformers(self):
245 def transformers(self):
246 """Return a list of checkers, sorted by priority."""
246 """Return a list of checkers, sorted by priority."""
247 return self._transformers
247 return self._transformers
248
248
249 def register_transformer(self, transformer):
249 def register_transformer(self, transformer):
250 """Register a transformer instance."""
250 """Register a transformer instance."""
251 if transformer not in self._transformers:
251 if transformer not in self._transformers:
252 self._transformers.append(transformer)
252 self._transformers.append(transformer)
253 self.sort_transformers()
253 self.sort_transformers()
254
254
255 def unregister_transformer(self, transformer):
255 def unregister_transformer(self, transformer):
256 """Unregister a transformer instance."""
256 """Unregister a transformer instance."""
257 if transformer in self._transformers:
257 if transformer in self._transformers:
258 self._transformers.remove(transformer)
258 self._transformers.remove(transformer)
259
259
260 #-------------------------------------------------------------------------
260 #-------------------------------------------------------------------------
261 # API for managing checkers
261 # API for managing checkers
262 #-------------------------------------------------------------------------
262 #-------------------------------------------------------------------------
263
263
264 def init_checkers(self):
264 def init_checkers(self):
265 """Create the default checkers."""
265 """Create the default checkers."""
266 self._checkers = []
266 self._checkers = []
267 for checker in _default_checkers:
267 for checker in _default_checkers:
268 checker(self, config=self.config)
268 checker(self, config=self.config)
269
269
270 def sort_checkers(self):
270 def sort_checkers(self):
271 """Sort the checkers by priority.
271 """Sort the checkers by priority.
272
272
273 This must be called after the priority of a checker is changed.
273 This must be called after the priority of a checker is changed.
274 The :meth:`register_checker` method calls this automatically.
274 The :meth:`register_checker` method calls this automatically.
275 """
275 """
276 self._checkers.sort(cmp=lambda x,y: x.priority-y.priority)
276 self._checkers.sort(cmp=lambda x,y: x.priority-y.priority)
277
277
278 @property
278 @property
279 def checkers(self):
279 def checkers(self):
280 """Return a list of checkers, sorted by priority."""
280 """Return a list of checkers, sorted by priority."""
281 return self._checkers
281 return self._checkers
282
282
283 def register_checker(self, checker):
283 def register_checker(self, checker):
284 """Register a checker instance."""
284 """Register a checker instance."""
285 if checker not in self._checkers:
285 if checker not in self._checkers:
286 self._checkers.append(checker)
286 self._checkers.append(checker)
287 self.sort_checkers()
287 self.sort_checkers()
288
288
289 def unregister_checker(self, checker):
289 def unregister_checker(self, checker):
290 """Unregister a checker instance."""
290 """Unregister a checker instance."""
291 if checker in self._checkers:
291 if checker in self._checkers:
292 self._checkers.remove(checker)
292 self._checkers.remove(checker)
293
293
294 #-------------------------------------------------------------------------
294 #-------------------------------------------------------------------------
295 # API for managing checkers
295 # API for managing checkers
296 #-------------------------------------------------------------------------
296 #-------------------------------------------------------------------------
297
297
298 def init_handlers(self):
298 def init_handlers(self):
299 """Create the default handlers."""
299 """Create the default handlers."""
300 self._handlers = {}
300 self._handlers = {}
301 self._esc_handlers = {}
301 self._esc_handlers = {}
302 for handler in _default_handlers:
302 for handler in _default_handlers:
303 handler(self, config=self.config)
303 handler(self, config=self.config)
304
304
305 @property
305 @property
306 def handlers(self):
306 def handlers(self):
307 """Return a dict of all the handlers."""
307 """Return a dict of all the handlers."""
308 return self._handlers
308 return self._handlers
309
309
310 def register_handler(self, name, handler, esc_strings):
310 def register_handler(self, name, handler, esc_strings):
311 """Register a handler instance by name with esc_strings."""
311 """Register a handler instance by name with esc_strings."""
312 self._handlers[name] = handler
312 self._handlers[name] = handler
313 for esc_str in esc_strings:
313 for esc_str in esc_strings:
314 self._esc_handlers[esc_str] = handler
314 self._esc_handlers[esc_str] = handler
315
315
316 def unregister_handler(self, name, handler, esc_strings):
316 def unregister_handler(self, name, handler, esc_strings):
317 """Unregister a handler instance by name with esc_strings."""
317 """Unregister a handler instance by name with esc_strings."""
318 try:
318 try:
319 del self._handlers[name]
319 del self._handlers[name]
320 except KeyError:
320 except KeyError:
321 pass
321 pass
322 for esc_str in esc_strings:
322 for esc_str in esc_strings:
323 h = self._esc_handlers.get(esc_str)
323 h = self._esc_handlers.get(esc_str)
324 if h is handler:
324 if h is handler:
325 del self._esc_handlers[esc_str]
325 del self._esc_handlers[esc_str]
326
326
327 def get_handler_by_name(self, name):
327 def get_handler_by_name(self, name):
328 """Get a handler by its name."""
328 """Get a handler by its name."""
329 return self._handlers.get(name)
329 return self._handlers.get(name)
330
330
331 def get_handler_by_esc(self, esc_str):
331 def get_handler_by_esc(self, esc_str):
332 """Get a handler by its escape string."""
332 """Get a handler by its escape string."""
333 return self._esc_handlers.get(esc_str)
333 return self._esc_handlers.get(esc_str)
334
334
335 #-------------------------------------------------------------------------
335 #-------------------------------------------------------------------------
336 # Main prefiltering API
336 # Main prefiltering API
337 #-------------------------------------------------------------------------
337 #-------------------------------------------------------------------------
338
338
339 def prefilter_line_info(self, line_info):
339 def prefilter_line_info(self, line_info):
340 """Prefilter a line that has been converted to a LineInfo object.
340 """Prefilter a line that has been converted to a LineInfo object.
341
341
342 This implements the checker/handler part of the prefilter pipe.
342 This implements the checker/handler part of the prefilter pipe.
343 """
343 """
344 # print "prefilter_line_info: ", line_info
344 # print "prefilter_line_info: ", line_info
345 handler = self.find_handler(line_info)
345 handler = self.find_handler(line_info)
346 return handler.handle(line_info)
346 return handler.handle(line_info)
347
347
348 def find_handler(self, line_info):
348 def find_handler(self, line_info):
349 """Find a handler for the line_info by trying checkers."""
349 """Find a handler for the line_info by trying checkers."""
350 for checker in self.checkers:
350 for checker in self.checkers:
351 if checker.enabled:
351 if checker.enabled:
352 handler = checker.check(line_info)
352 handler = checker.check(line_info)
353 if handler:
353 if handler:
354 return handler
354 return handler
355 return self.get_handler_by_name('normal')
355 return self.get_handler_by_name('normal')
356
356
357 def transform_line(self, line, continue_prompt):
357 def transform_line(self, line, continue_prompt):
358 """Calls the enabled transformers in order of increasing priority."""
358 """Calls the enabled transformers in order of increasing priority."""
359 for transformer in self.transformers:
359 for transformer in self.transformers:
360 if transformer.enabled:
360 if transformer.enabled:
361 line = transformer.transform(line, continue_prompt)
361 line = transformer.transform(line, continue_prompt)
362 return line
362 return line
363
363
364 def prefilter_line(self, line, continue_prompt=False):
364 def prefilter_line(self, line, continue_prompt=False):
365 """Prefilter a single input line as text.
365 """Prefilter a single input line as text.
366
366
367 This method prefilters a single line of text by calling the
367 This method prefilters a single line of text by calling the
368 transformers and then the checkers/handlers.
368 transformers and then the checkers/handlers.
369 """
369 """
370
370
371 # print "prefilter_line: ", line, continue_prompt
371 # print "prefilter_line: ", line, continue_prompt
372 # All handlers *must* return a value, even if it's blank ('').
372 # All handlers *must* return a value, even if it's blank ('').
373
373
374 # Lines are NOT logged here. Handlers should process the line as
374 # Lines are NOT logged here. Handlers should process the line as
375 # needed, update the cache AND log it (so that the input cache array
375 # needed, update the cache AND log it (so that the input cache array
376 # stays synced).
376 # stays synced).
377
377
378 # save the line away in case we crash, so the post-mortem handler can
378 # save the line away in case we crash, so the post-mortem handler can
379 # record it
379 # record it
380 self.shell._last_input_line = line
380 self.shell._last_input_line = line
381
381
382 if not line:
382 if not line:
383 # Return immediately on purely empty lines, so that if the user
383 # Return immediately on purely empty lines, so that if the user
384 # previously typed some whitespace that started a continuation
384 # previously typed some whitespace that started a continuation
385 # prompt, he can break out of that loop with just an empty line.
385 # prompt, he can break out of that loop with just an empty line.
386 # This is how the default python prompt works.
386 # This is how the default python prompt works.
387
387
388 # Only return if the accumulated input buffer was just whitespace!
388 # Only return if the accumulated input buffer was just whitespace!
389 if ''.join(self.shell.buffer).isspace():
389 if ''.join(self.shell.buffer).isspace():
390 self.shell.buffer[:] = []
390 self.shell.buffer[:] = []
391 return ''
391 return ''
392
392
393 # At this point, we invoke our transformers.
393 # At this point, we invoke our transformers.
394 if not continue_prompt or (continue_prompt and self.multi_line_specials):
394 if not continue_prompt or (continue_prompt and self.multi_line_specials):
395 line = self.transform_line(line, continue_prompt)
395 line = self.transform_line(line, continue_prompt)
396
396
397 # Now we compute line_info for the checkers and handlers
397 # Now we compute line_info for the checkers and handlers
398 line_info = LineInfo(line, continue_prompt)
398 line_info = LineInfo(line, continue_prompt)
399
399
400 # the input history needs to track even empty lines
400 # the input history needs to track even empty lines
401 stripped = line.strip()
401 stripped = line.strip()
402
402
403 normal_handler = self.get_handler_by_name('normal')
403 normal_handler = self.get_handler_by_name('normal')
404 if not stripped:
404 if not stripped:
405 if not continue_prompt:
405 if not continue_prompt:
406 self.shell.outputcache.prompt_count -= 1
406 self.shell.outputcache.prompt_count -= 1
407
407
408 return normal_handler.handle(line_info)
408 return normal_handler.handle(line_info)
409
409
410 # special handlers are only allowed for single line statements
410 # special handlers are only allowed for single line statements
411 if continue_prompt and not self.multi_line_specials:
411 if continue_prompt and not self.multi_line_specials:
412 return normal_handler.handle(line_info)
412 return normal_handler.handle(line_info)
413
413
414 prefiltered = self.prefilter_line_info(line_info)
414 prefiltered = self.prefilter_line_info(line_info)
415 # print "prefiltered line: %r" % prefiltered
415 # print "prefiltered line: %r" % prefiltered
416 return prefiltered
416 return prefiltered
417
417
418 def prefilter_lines(self, lines, continue_prompt=False):
418 def prefilter_lines(self, lines, continue_prompt=False):
419 """Prefilter multiple input lines of text.
419 """Prefilter multiple input lines of text.
420
420
421 This is the main entry point for prefiltering multiple lines of
421 This is the main entry point for prefiltering multiple lines of
422 input. This simply calls :meth:`prefilter_line` for each line of
422 input. This simply calls :meth:`prefilter_line` for each line of
423 input.
423 input.
424
424
425 This covers cases where there are multiple lines in the user entry,
425 This covers cases where there are multiple lines in the user entry,
426 which is the case when the user goes back to a multiline history
426 which is the case when the user goes back to a multiline history
427 entry and presses enter.
427 entry and presses enter.
428 """
428 """
429 llines = lines.rstrip('\n').split('\n')
429 llines = lines.rstrip('\n').split('\n')
430 # We can get multiple lines in one shot, where multiline input 'blends'
430 # We can get multiple lines in one shot, where multiline input 'blends'
431 # into one line, in cases like recalling from the readline history
431 # into one line, in cases like recalling from the readline history
432 # buffer. We need to make sure that in such cases, we correctly
432 # buffer. We need to make sure that in such cases, we correctly
433 # communicate downstream which line is first and which are continuation
433 # communicate downstream which line is first and which are continuation
434 # ones.
434 # ones.
435 if len(llines) > 1:
435 if len(llines) > 1:
436 out = '\n'.join([self.prefilter_line(line, lnum>0)
436 out = '\n'.join([self.prefilter_line(line, lnum>0)
437 for lnum, line in enumerate(llines) ])
437 for lnum, line in enumerate(llines) ])
438 else:
438 else:
439 out = self.prefilter_line(llines[0], continue_prompt)
439 out = self.prefilter_line(llines[0], continue_prompt)
440
440
441 return out
441 return out
442
442
443 #-----------------------------------------------------------------------------
443 #-----------------------------------------------------------------------------
444 # Prefilter transformers
444 # Prefilter transformers
445 #-----------------------------------------------------------------------------
445 #-----------------------------------------------------------------------------
446
446
447
447
448 class PrefilterTransformer(Component):
448 class PrefilterTransformer(Component):
449 """Transform a line of user input."""
449 """Transform a line of user input."""
450
450
451 priority = Int(100, config=True)
451 priority = Int(100, config=True)
452 shell = Any
452 shell = Any
453 prefilter_manager = Any
453 prefilter_manager = Any
454 enabled = Bool(True, config=True)
454 enabled = Bool(True, config=True)
455
455
456 def __init__(self, parent, config=None):
456 def __init__(self, parent, config=None):
457 super(PrefilterTransformer, self).__init__(parent, config=config)
457 super(PrefilterTransformer, self).__init__(parent, config=config)
458 self.prefilter_manager.register_transformer(self)
458 self.prefilter_manager.register_transformer(self)
459
459
460 @auto_attr
460 @auto_attr
461 def shell(self):
461 def shell(self):
462 return Component.get_instances(
462 return Component.get_instances(
463 root=self.root,
463 root=self.root,
464 klass='IPython.core.iplib.InteractiveShell')[0]
464 klass='IPython.core.iplib.InteractiveShell')[0]
465
465
466 @auto_attr
466 @auto_attr
467 def prefilter_manager(self):
467 def prefilter_manager(self):
468 return PrefilterManager.get_instances(root=self.root)[0]
468 return PrefilterManager.get_instances(root=self.root)[0]
469
469
470 def transform(self, line, continue_prompt):
470 def transform(self, line, continue_prompt):
471 """Transform a line, returning the new one."""
471 """Transform a line, returning the new one."""
472 return None
472 return None
473
473
474 def __repr__(self):
474 def __repr__(self):
475 return "<%s(priority=%r, enabled=%r)>" % (
475 return "<%s(priority=%r, enabled=%r)>" % (
476 self.__class__.__name__, self.priority, self.enabled)
476 self.__class__.__name__, self.priority, self.enabled)
477
477
478
478
479 _assign_system_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
479 _assign_system_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
480 r'\s*=\s*!(?P<cmd>.*)')
480 r'\s*=\s*!(?P<cmd>.*)')
481
481
482
482
483 class AssignSystemTransformer(PrefilterTransformer):
483 class AssignSystemTransformer(PrefilterTransformer):
484 """Handle the `files = !ls` syntax."""
484 """Handle the `files = !ls` syntax."""
485
485
486 priority = Int(100, config=True)
486 priority = Int(100, config=True)
487
487
488 def transform(self, line, continue_prompt):
488 def transform(self, line, continue_prompt):
489 m = _assign_system_re.match(line)
489 m = _assign_system_re.match(line)
490 if m is not None:
490 if m is not None:
491 cmd = m.group('cmd')
491 cmd = m.group('cmd')
492 lhs = m.group('lhs')
492 lhs = m.group('lhs')
493 expr = make_quoted_expr("sc -l =%s" % cmd)
493 expr = make_quoted_expr("sc -l =%s" % cmd)
494 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
494 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
495 return new_line
495 return new_line
496 return line
496 return line
497
497
498
498
499 _assign_magic_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
499 _assign_magic_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
500 r'\s*=\s*%(?P<cmd>.*)')
500 r'\s*=\s*%(?P<cmd>.*)')
501
501
502 class AssignMagicTransformer(PrefilterTransformer):
502 class AssignMagicTransformer(PrefilterTransformer):
503 """Handle the `a = %who` syntax."""
503 """Handle the `a = %who` syntax."""
504
504
505 priority = Int(200, config=True)
505 priority = Int(200, config=True)
506
506
507 def transform(self, line, continue_prompt):
507 def transform(self, line, continue_prompt):
508 m = _assign_magic_re.match(line)
508 m = _assign_magic_re.match(line)
509 if m is not None:
509 if m is not None:
510 cmd = m.group('cmd')
510 cmd = m.group('cmd')
511 lhs = m.group('lhs')
511 lhs = m.group('lhs')
512 expr = make_quoted_expr(cmd)
512 expr = make_quoted_expr(cmd)
513 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
513 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
514 return new_line
514 return new_line
515 return line
515 return line
516
516
517
517
518 _classic_prompt_re = re.compile(r'(^[ \t]*>>> |^[ \t]*\.\.\. )')
518 _classic_prompt_re = re.compile(r'(^[ \t]*>>> |^[ \t]*\.\.\. )')
519
519
520 class PyPromptTransformer(PrefilterTransformer):
520 class PyPromptTransformer(PrefilterTransformer):
521 """Handle inputs that start with '>>> ' syntax."""
521 """Handle inputs that start with '>>> ' syntax."""
522
522
523 priority = Int(50, config=True)
523 priority = Int(50, config=True)
524
524
525 def transform(self, line, continue_prompt):
525 def transform(self, line, continue_prompt):
526
526
527 if not line or line.isspace() or line.strip() == '...':
527 if not line or line.isspace() or line.strip() == '...':
528 # This allows us to recognize multiple input prompts separated by
528 # This allows us to recognize multiple input prompts separated by
529 # blank lines and pasted in a single chunk, very common when
529 # blank lines and pasted in a single chunk, very common when
530 # pasting doctests or long tutorial passages.
530 # pasting doctests or long tutorial passages.
531 return ''
531 return ''
532 m = _classic_prompt_re.match(line)
532 m = _classic_prompt_re.match(line)
533 if m:
533 if m:
534 return line[len(m.group(0)):]
534 return line[len(m.group(0)):]
535 else:
535 else:
536 return line
536 return line
537
537
538
538
539 _ipy_prompt_re = re.compile(r'(^[ \t]*In \[\d+\]: |^[ \t]*\ \ \ \.\.\.+: )')
539 _ipy_prompt_re = re.compile(r'(^[ \t]*In \[\d+\]: |^[ \t]*\ \ \ \.\.\.+: )')
540
540
541 class IPyPromptTransformer(PrefilterTransformer):
541 class IPyPromptTransformer(PrefilterTransformer):
542 """Handle inputs that start classic IPython prompt syntax."""
542 """Handle inputs that start classic IPython prompt syntax."""
543
543
544 priority = Int(50, config=True)
544 priority = Int(50, config=True)
545
545
546 def transform(self, line, continue_prompt):
546 def transform(self, line, continue_prompt):
547
547
548 if not line or line.isspace() or line.strip() == '...':
548 if not line or line.isspace() or line.strip() == '...':
549 # This allows us to recognize multiple input prompts separated by
549 # This allows us to recognize multiple input prompts separated by
550 # blank lines and pasted in a single chunk, very common when
550 # blank lines and pasted in a single chunk, very common when
551 # pasting doctests or long tutorial passages.
551 # pasting doctests or long tutorial passages.
552 return ''
552 return ''
553 m = _ipy_prompt_re.match(line)
553 m = _ipy_prompt_re.match(line)
554 if m:
554 if m:
555 return line[len(m.group(0)):]
555 return line[len(m.group(0)):]
556 else:
556 else:
557 return line
557 return line
558
558
559 #-----------------------------------------------------------------------------
559 #-----------------------------------------------------------------------------
560 # Prefilter checkers
560 # Prefilter checkers
561 #-----------------------------------------------------------------------------
561 #-----------------------------------------------------------------------------
562
562
563
563
564 class PrefilterChecker(Component):
564 class PrefilterChecker(Component):
565 """Inspect an input line and return a handler for that line."""
565 """Inspect an input line and return a handler for that line."""
566
566
567 priority = Int(100, config=True)
567 priority = Int(100, config=True)
568 shell = Any
568 shell = Any
569 prefilter_manager = Any
569 prefilter_manager = Any
570 enabled = Bool(True, config=True)
570 enabled = Bool(True, config=True)
571
571
572 def __init__(self, parent, config=None):
572 def __init__(self, parent, config=None):
573 super(PrefilterChecker, self).__init__(parent, config=config)
573 super(PrefilterChecker, self).__init__(parent, config=config)
574 self.prefilter_manager.register_checker(self)
574 self.prefilter_manager.register_checker(self)
575
575
576 @auto_attr
576 @auto_attr
577 def shell(self):
577 def shell(self):
578 return Component.get_instances(
578 return Component.get_instances(
579 root=self.root,
579 root=self.root,
580 klass='IPython.core.iplib.InteractiveShell')[0]
580 klass='IPython.core.iplib.InteractiveShell')[0]
581
581
582 @auto_attr
582 @auto_attr
583 def prefilter_manager(self):
583 def prefilter_manager(self):
584 return PrefilterManager.get_instances(root=self.root)[0]
584 return PrefilterManager.get_instances(root=self.root)[0]
585
585
586 def check(self, line_info):
586 def check(self, line_info):
587 """Inspect line_info and return a handler instance or None."""
587 """Inspect line_info and return a handler instance or None."""
588 return None
588 return None
589
589
590 def __repr__(self):
590 def __repr__(self):
591 return "<%s(priority=%r, enabled=%r)>" % (
591 return "<%s(priority=%r, enabled=%r)>" % (
592 self.__class__.__name__, self.priority, self.enabled)
592 self.__class__.__name__, self.priority, self.enabled)
593
593
594
594
595 class EmacsChecker(PrefilterChecker):
595 class EmacsChecker(PrefilterChecker):
596
596
597 priority = Int(100, config=True)
597 priority = Int(100, config=True)
598 enabled = Bool(False, config=True)
598 enabled = Bool(False, config=True)
599
599
600 def check(self, line_info):
600 def check(self, line_info):
601 "Emacs ipython-mode tags certain input lines."
601 "Emacs ipython-mode tags certain input lines."
602 if line_info.line.endswith('# PYTHON-MODE'):
602 if line_info.line.endswith('# PYTHON-MODE'):
603 return self.prefilter_manager.get_handler_by_name('emacs')
603 return self.prefilter_manager.get_handler_by_name('emacs')
604 else:
604 else:
605 return None
605 return None
606
606
607
607
608 class ShellEscapeChecker(PrefilterChecker):
608 class ShellEscapeChecker(PrefilterChecker):
609
609
610 priority = Int(200, config=True)
610 priority = Int(200, config=True)
611
611
612 def check(self, line_info):
612 def check(self, line_info):
613 if line_info.line.lstrip().startswith(ESC_SHELL):
613 if line_info.line.lstrip().startswith(ESC_SHELL):
614 return self.prefilter_manager.get_handler_by_name('shell')
614 return self.prefilter_manager.get_handler_by_name('shell')
615
615
616
616
617 class IPyAutocallChecker(PrefilterChecker):
617 class IPyAutocallChecker(PrefilterChecker):
618
618
619 priority = Int(300, config=True)
619 priority = Int(300, config=True)
620
620
621 def check(self, line_info):
621 def check(self, line_info):
622 "Instances of IPyAutocall in user_ns get autocalled immediately"
622 "Instances of IPyAutocall in user_ns get autocalled immediately"
623 obj = self.shell.user_ns.get(line_info.ifun, None)
623 obj = self.shell.user_ns.get(line_info.ifun, None)
624 if isinstance(obj, IPyAutocall):
624 if isinstance(obj, IPyAutocall):
625 obj.set_ip(self.shell)
625 obj.set_ip(self.shell)
626 return self.prefilter_manager.get_handler_by_name('auto')
626 return self.prefilter_manager.get_handler_by_name('auto')
627 else:
627 else:
628 return None
628 return None
629
629
630
630
631 class MultiLineMagicChecker(PrefilterChecker):
631 class MultiLineMagicChecker(PrefilterChecker):
632
632
633 priority = Int(400, config=True)
633 priority = Int(400, config=True)
634
634
635 def check(self, line_info):
635 def check(self, line_info):
636 "Allow ! and !! in multi-line statements if multi_line_specials is on"
636 "Allow ! and !! in multi-line statements if multi_line_specials is on"
637 # Note that this one of the only places we check the first character of
637 # Note that this one of the only places we check the first character of
638 # ifun and *not* the pre_char. Also note that the below test matches
638 # ifun and *not* the pre_char. Also note that the below test matches
639 # both ! and !!.
639 # both ! and !!.
640 if line_info.continue_prompt \
640 if line_info.continue_prompt \
641 and self.prefilter_manager.multi_line_specials:
641 and self.prefilter_manager.multi_line_specials:
642 if line_info.ifun.startswith(ESC_MAGIC):
642 if line_info.ifun.startswith(ESC_MAGIC):
643 return self.prefilter_manager.get_handler_by_name('magic')
643 return self.prefilter_manager.get_handler_by_name('magic')
644 else:
644 else:
645 return None
645 return None
646
646
647
647
648 class EscCharsChecker(PrefilterChecker):
648 class EscCharsChecker(PrefilterChecker):
649
649
650 priority = Int(500, config=True)
650 priority = Int(500, config=True)
651
651
652 def check(self, line_info):
652 def check(self, line_info):
653 """Check for escape character and return either a handler to handle it,
653 """Check for escape character and return either a handler to handle it,
654 or None if there is no escape char."""
654 or None if there is no escape char."""
655 if line_info.line[-1] == ESC_HELP \
655 if line_info.line[-1] == ESC_HELP \
656 and line_info.pre_char != ESC_SHELL \
656 and line_info.pre_char != ESC_SHELL \
657 and line_info.pre_char != ESC_SH_CAP:
657 and line_info.pre_char != ESC_SH_CAP:
658 # the ? can be at the end, but *not* for either kind of shell escape,
658 # the ? can be at the end, but *not* for either kind of shell escape,
659 # because a ? can be a vaild final char in a shell cmd
659 # because a ? can be a vaild final char in a shell cmd
660 return self.prefilter_manager.get_handler_by_name('help')
660 return self.prefilter_manager.get_handler_by_name('help')
661 else:
661 else:
662 # This returns None like it should if no handler exists
662 # This returns None like it should if no handler exists
663 return self.prefilter_manager.get_handler_by_esc(line_info.pre_char)
663 return self.prefilter_manager.get_handler_by_esc(line_info.pre_char)
664
664
665
665
666 class AssignmentChecker(PrefilterChecker):
666 class AssignmentChecker(PrefilterChecker):
667
667
668 priority = Int(600, config=True)
668 priority = Int(600, config=True)
669
669
670 def check(self, line_info):
670 def check(self, line_info):
671 """Check to see if user is assigning to a var for the first time, in
671 """Check to see if user is assigning to a var for the first time, in
672 which case we want to avoid any sort of automagic / autocall games.
672 which case we want to avoid any sort of automagic / autocall games.
673
673
674 This allows users to assign to either alias or magic names true python
674 This allows users to assign to either alias or magic names true python
675 variables (the magic/alias systems always take second seat to true
675 variables (the magic/alias systems always take second seat to true
676 python code). E.g. ls='hi', or ls,that=1,2"""
676 python code). E.g. ls='hi', or ls,that=1,2"""
677 if line_info.the_rest:
677 if line_info.the_rest:
678 if line_info.the_rest[0] in '=,':
678 if line_info.the_rest[0] in '=,':
679 return self.prefilter_manager.get_handler_by_name('normal')
679 return self.prefilter_manager.get_handler_by_name('normal')
680 else:
680 else:
681 return None
681 return None
682
682
683
683
684 class AutoMagicChecker(PrefilterChecker):
684 class AutoMagicChecker(PrefilterChecker):
685
685
686 priority = Int(700, config=True)
686 priority = Int(700, config=True)
687
687
688 def check(self, line_info):
688 def check(self, line_info):
689 """If the ifun is magic, and automagic is on, run it. Note: normal,
689 """If the ifun is magic, and automagic is on, run it. Note: normal,
690 non-auto magic would already have been triggered via '%' in
690 non-auto magic would already have been triggered via '%' in
691 check_esc_chars. This just checks for automagic. Also, before
691 check_esc_chars. This just checks for automagic. Also, before
692 triggering the magic handler, make sure that there is nothing in the
692 triggering the magic handler, make sure that there is nothing in the
693 user namespace which could shadow it."""
693 user namespace which could shadow it."""
694 if not self.shell.automagic or not hasattr(self.shell,'magic_'+line_info.ifun):
694 if not self.shell.automagic or not hasattr(self.shell,'magic_'+line_info.ifun):
695 return None
695 return None
696
696
697 # We have a likely magic method. Make sure we should actually call it.
697 # We have a likely magic method. Make sure we should actually call it.
698 if line_info.continue_prompt and not self.prefilter_manager.multi_line_specials:
698 if line_info.continue_prompt and not self.prefilter_manager.multi_line_specials:
699 return None
699 return None
700
700
701 head = line_info.ifun.split('.',1)[0]
701 head = line_info.ifun.split('.',1)[0]
702 if is_shadowed(head, self.shell):
702 if is_shadowed(head, self.shell):
703 return None
703 return None
704
704
705 return self.prefilter_manager.get_handler_by_name('magic')
705 return self.prefilter_manager.get_handler_by_name('magic')
706
706
707
707
708 class AliasChecker(PrefilterChecker):
708 class AliasChecker(PrefilterChecker):
709
709
710 priority = Int(800, config=True)
710 priority = Int(800, config=True)
711
711
712 @auto_attr
712 @auto_attr
713 def alias_manager(self):
713 def alias_manager(self):
714 return AliasManager.get_instances(root=self.root)[0]
714 return AliasManager.get_instances(root=self.root)[0]
715
715
716 def check(self, line_info):
716 def check(self, line_info):
717 "Check if the initital identifier on the line is an alias."
717 "Check if the initital identifier on the line is an alias."
718 # Note: aliases can not contain '.'
718 # Note: aliases can not contain '.'
719 head = line_info.ifun.split('.',1)[0]
719 head = line_info.ifun.split('.',1)[0]
720 if line_info.ifun not in self.alias_manager \
720 if line_info.ifun not in self.alias_manager \
721 or head not in self.alias_manager \
721 or head not in self.alias_manager \
722 or is_shadowed(head, self.shell):
722 or is_shadowed(head, self.shell):
723 return None
723 return None
724
724
725 return self.prefilter_manager.get_handler_by_name('alias')
725 return self.prefilter_manager.get_handler_by_name('alias')
726
726
727
727
728 class PythonOpsChecker(PrefilterChecker):
728 class PythonOpsChecker(PrefilterChecker):
729
729
730 priority = Int(900, config=True)
730 priority = Int(900, config=True)
731
731
732 def check(self, line_info):
732 def check(self, line_info):
733 """If the 'rest' of the line begins with a function call or pretty much
733 """If the 'rest' of the line begins with a function call or pretty much
734 any python operator, we should simply execute the line (regardless of
734 any python operator, we should simply execute the line (regardless of
735 whether or not there's a possible autocall expansion). This avoids
735 whether or not there's a possible autocall expansion). This avoids
736 spurious (and very confusing) geattr() accesses."""
736 spurious (and very confusing) geattr() accesses."""
737 if line_info.the_rest and line_info.the_rest[0] in '!=()<>,+*/%^&|':
737 if line_info.the_rest and line_info.the_rest[0] in '!=()<>,+*/%^&|':
738 return self.prefilter_manager.get_handler_by_name('normal')
738 return self.prefilter_manager.get_handler_by_name('normal')
739 else:
739 else:
740 return None
740 return None
741
741
742
742
743 class AutocallChecker(PrefilterChecker):
743 class AutocallChecker(PrefilterChecker):
744
744
745 priority = Int(1000, config=True)
745 priority = Int(1000, config=True)
746
746
747 def check(self, line_info):
747 def check(self, line_info):
748 "Check if the initial word/function is callable and autocall is on."
748 "Check if the initial word/function is callable and autocall is on."
749 if not self.shell.autocall:
749 if not self.shell.autocall:
750 return None
750 return None
751
751
752 oinfo = line_info.ofind(self.shell) # This can mutate state via getattr
752 oinfo = line_info.ofind(self.shell) # This can mutate state via getattr
753 if not oinfo['found']:
753 if not oinfo['found']:
754 return None
754 return None
755
755
756 if callable(oinfo['obj']) \
756 if callable(oinfo['obj']) \
757 and (not re_exclude_auto.match(line_info.the_rest)) \
757 and (not re_exclude_auto.match(line_info.the_rest)) \
758 and re_fun_name.match(line_info.ifun):
758 and re_fun_name.match(line_info.ifun):
759 return self.prefilter_manager.get_handler_by_name('auto')
759 return self.prefilter_manager.get_handler_by_name('auto')
760 else:
760 else:
761 return None
761 return None
762
762
763
763
764 #-----------------------------------------------------------------------------
764 #-----------------------------------------------------------------------------
765 # Prefilter handlers
765 # Prefilter handlers
766 #-----------------------------------------------------------------------------
766 #-----------------------------------------------------------------------------
767
767
768
768
769 class PrefilterHandler(Component):
769 class PrefilterHandler(Component):
770
770
771 handler_name = Str('normal')
771 handler_name = Str('normal')
772 esc_strings = List([])
772 esc_strings = List([])
773 shell = Any
773 shell = Any
774 prefilter_manager = Any
774 prefilter_manager = Any
775
775
776 def __init__(self, parent, config=None):
776 def __init__(self, parent, config=None):
777 super(PrefilterHandler, self).__init__(parent, config=config)
777 super(PrefilterHandler, self).__init__(parent, config=config)
778 self.prefilter_manager.register_handler(
778 self.prefilter_manager.register_handler(
779 self.handler_name,
779 self.handler_name,
780 self,
780 self,
781 self.esc_strings
781 self.esc_strings
782 )
782 )
783
783
784 @auto_attr
784 @auto_attr
785 def shell(self):
785 def shell(self):
786 return Component.get_instances(
786 return Component.get_instances(
787 root=self.root,
787 root=self.root,
788 klass='IPython.core.iplib.InteractiveShell')[0]
788 klass='IPython.core.iplib.InteractiveShell')[0]
789
789
790 @auto_attr
790 @auto_attr
791 def prefilter_manager(self):
791 def prefilter_manager(self):
792 return PrefilterManager.get_instances(root=self.root)[0]
792 return PrefilterManager.get_instances(root=self.root)[0]
793
793
794 def handle(self, line_info):
794 def handle(self, line_info):
795 # print "normal: ", line_info
795 # print "normal: ", line_info
796 """Handle normal input lines. Use as a template for handlers."""
796 """Handle normal input lines. Use as a template for handlers."""
797
797
798 # With autoindent on, we need some way to exit the input loop, and I
798 # With autoindent on, we need some way to exit the input loop, and I
799 # don't want to force the user to have to backspace all the way to
799 # don't want to force the user to have to backspace all the way to
800 # clear the line. The rule will be in this case, that either two
800 # clear the line. The rule will be in this case, that either two
801 # lines of pure whitespace in a row, or a line of pure whitespace but
801 # lines of pure whitespace in a row, or a line of pure whitespace but
802 # of a size different to the indent level, will exit the input loop.
802 # of a size different to the indent level, will exit the input loop.
803 line = line_info.line
803 line = line_info.line
804 continue_prompt = line_info.continue_prompt
804 continue_prompt = line_info.continue_prompt
805
805
806 if (continue_prompt and
806 if (continue_prompt and
807 self.shell.autoindent and
807 self.shell.autoindent and
808 line.isspace() and
808 line.isspace() and
809
809
810 (0 < abs(len(line) - self.shell.indent_current_nsp) <= 2
810 (0 < abs(len(line) - self.shell.indent_current_nsp) <= 2
811 or
811 or
812 not self.shell.buffer
812 not self.shell.buffer
813 or
813 or
814 (self.shell.buffer[-1]).isspace()
814 (self.shell.buffer[-1]).isspace()
815 )
815 )
816 ):
816 ):
817 line = ''
817 line = ''
818
818
819 self.shell.log(line, line, continue_prompt)
819 self.shell.log(line, line, continue_prompt)
820 return line
820 return line
821
821
822 def __str__(self):
822 def __str__(self):
823 return "<%s(name=%s)>" % (self.__class__.__name__, self.handler_name)
823 return "<%s(name=%s)>" % (self.__class__.__name__, self.handler_name)
824
824
825
825
826 class AliasHandler(PrefilterHandler):
826 class AliasHandler(PrefilterHandler):
827
827
828 handler_name = Str('alias')
828 handler_name = Str('alias')
829
829
830 @auto_attr
830 @auto_attr
831 def alias_manager(self):
831 def alias_manager(self):
832 return AliasManager.get_instances(root=self.root)[0]
832 return AliasManager.get_instances(root=self.root)[0]
833
833
834 def handle(self, line_info):
834 def handle(self, line_info):
835 """Handle alias input lines. """
835 """Handle alias input lines. """
836 transformed = self.alias_manager.expand_aliases(line_info.ifun,line_info.the_rest)
836 transformed = self.alias_manager.expand_aliases(line_info.ifun,line_info.the_rest)
837 # pre is needed, because it carries the leading whitespace. Otherwise
837 # pre is needed, because it carries the leading whitespace. Otherwise
838 # aliases won't work in indented sections.
838 # aliases won't work in indented sections.
839 line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace,
839 line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace,
840 make_quoted_expr(transformed))
840 make_quoted_expr(transformed))
841
841
842 self.shell.log(line_info.line, line_out, line_info.continue_prompt)
842 self.shell.log(line_info.line, line_out, line_info.continue_prompt)
843 return line_out
843 return line_out
844
844
845
845
846 class ShellEscapeHandler(PrefilterHandler):
846 class ShellEscapeHandler(PrefilterHandler):
847
847
848 handler_name = Str('shell')
848 handler_name = Str('shell')
849 esc_strings = List([ESC_SHELL, ESC_SH_CAP])
849 esc_strings = List([ESC_SHELL, ESC_SH_CAP])
850
850
851 def handle(self, line_info):
851 def handle(self, line_info):
852 """Execute the line in a shell, empty return value"""
852 """Execute the line in a shell, empty return value"""
853 magic_handler = self.prefilter_manager.get_handler_by_name('magic')
853 magic_handler = self.prefilter_manager.get_handler_by_name('magic')
854
854
855 line = line_info.line
855 line = line_info.line
856 if line.lstrip().startswith(ESC_SH_CAP):
856 if line.lstrip().startswith(ESC_SH_CAP):
857 # rewrite LineInfo's line, ifun and the_rest to properly hold the
857 # rewrite LineInfo's line, ifun and the_rest to properly hold the
858 # call to %sx and the actual command to be executed, so
858 # call to %sx and the actual command to be executed, so
859 # handle_magic can work correctly. Note that this works even if
859 # handle_magic can work correctly. Note that this works even if
860 # the line is indented, so it handles multi_line_specials
860 # the line is indented, so it handles multi_line_specials
861 # properly.
861 # properly.
862 new_rest = line.lstrip()[2:]
862 new_rest = line.lstrip()[2:]
863 line_info.line = '%ssx %s' % (ESC_MAGIC, new_rest)
863 line_info.line = '%ssx %s' % (ESC_MAGIC, new_rest)
864 line_info.ifun = 'sx'
864 line_info.ifun = 'sx'
865 line_info.the_rest = new_rest
865 line_info.the_rest = new_rest
866 return magic_handler.handle(line_info)
866 return magic_handler.handle(line_info)
867 else:
867 else:
868 cmd = line.lstrip().lstrip(ESC_SHELL)
868 cmd = line.lstrip().lstrip(ESC_SHELL)
869 line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace,
869 line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace,
870 make_quoted_expr(cmd))
870 make_quoted_expr(cmd))
871 # update cache/log and return
871 # update cache/log and return
872 self.shell.log(line, line_out, line_info.continue_prompt)
872 self.shell.log(line, line_out, line_info.continue_prompt)
873 return line_out
873 return line_out
874
874
875
875
876 class MagicHandler(PrefilterHandler):
876 class MagicHandler(PrefilterHandler):
877
877
878 handler_name = Str('magic')
878 handler_name = Str('magic')
879 esc_strings = List([ESC_MAGIC])
879 esc_strings = List([ESC_MAGIC])
880
880
881 def handle(self, line_info):
881 def handle(self, line_info):
882 """Execute magic functions."""
882 """Execute magic functions."""
883 ifun = line_info.ifun
883 ifun = line_info.ifun
884 the_rest = line_info.the_rest
884 the_rest = line_info.the_rest
885 cmd = '%sget_ipython().magic(%s)' % (line_info.pre_whitespace,
885 cmd = '%sget_ipython().magic(%s)' % (line_info.pre_whitespace,
886 make_quoted_expr(ifun + " " + the_rest))
886 make_quoted_expr(ifun + " " + the_rest))
887 self.shell.log(line_info.line, cmd, line_info.continue_prompt)
887 self.shell.log(line_info.line, cmd, line_info.continue_prompt)
888 return cmd
888 return cmd
889
889
890
890
891 class AutoHandler(PrefilterHandler):
891 class AutoHandler(PrefilterHandler):
892
892
893 handler_name = Str('auto')
893 handler_name = Str('auto')
894 esc_strings = List([ESC_PAREN, ESC_QUOTE, ESC_QUOTE2])
894 esc_strings = List([ESC_PAREN, ESC_QUOTE, ESC_QUOTE2])
895
895
896 def handle(self, line_info):
896 def handle(self, line_info):
897 """Hande lines which can be auto-executed, quoting if requested."""
897 """Hande lines which can be auto-executed, quoting if requested."""
898 line = line_info.line
898 line = line_info.line
899 ifun = line_info.ifun
899 ifun = line_info.ifun
900 the_rest = line_info.the_rest
900 the_rest = line_info.the_rest
901 pre = line_info.pre
901 pre = line_info.pre
902 continue_prompt = line_info.continue_prompt
902 continue_prompt = line_info.continue_prompt
903 obj = line_info.ofind(self)['obj']
903 obj = line_info.ofind(self)['obj']
904 #print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun,the_rest) # dbg
904 #print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun,the_rest) # dbg
905
905
906 # This should only be active for single-line input!
906 # This should only be active for single-line input!
907 if continue_prompt:
907 if continue_prompt:
908 self.shell.log(line,line,continue_prompt)
908 self.shell.log(line,line,continue_prompt)
909 return line
909 return line
910
910
911 force_auto = isinstance(obj, IPyAutocall)
911 force_auto = isinstance(obj, IPyAutocall)
912 auto_rewrite = True
912 auto_rewrite = True
913
913
914 if pre == ESC_QUOTE:
914 if pre == ESC_QUOTE:
915 # Auto-quote splitting on whitespace
915 # Auto-quote splitting on whitespace
916 newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) )
916 newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) )
917 elif pre == ESC_QUOTE2:
917 elif pre == ESC_QUOTE2:
918 # Auto-quote whole string
918 # Auto-quote whole string
919 newcmd = '%s("%s")' % (ifun,the_rest)
919 newcmd = '%s("%s")' % (ifun,the_rest)
920 elif pre == ESC_PAREN:
920 elif pre == ESC_PAREN:
921 newcmd = '%s(%s)' % (ifun,",".join(the_rest.split()))
921 newcmd = '%s(%s)' % (ifun,",".join(the_rest.split()))
922 else:
922 else:
923 # Auto-paren.
923 # Auto-paren.
924 # We only apply it to argument-less calls if the autocall
924 # We only apply it to argument-less calls if the autocall
925 # parameter is set to 2. We only need to check that autocall is <
925 # parameter is set to 2. We only need to check that autocall is <
926 # 2, since this function isn't called unless it's at least 1.
926 # 2, since this function isn't called unless it's at least 1.
927 if not the_rest and (self.shell.autocall < 2) and not force_auto:
927 if not the_rest and (self.shell.autocall < 2) and not force_auto:
928 newcmd = '%s %s' % (ifun,the_rest)
928 newcmd = '%s %s' % (ifun,the_rest)
929 auto_rewrite = False
929 auto_rewrite = False
930 else:
930 else:
931 if not force_auto and the_rest.startswith('['):
931 if not force_auto and the_rest.startswith('['):
932 if hasattr(obj,'__getitem__'):
932 if hasattr(obj,'__getitem__'):
933 # Don't autocall in this case: item access for an object
933 # Don't autocall in this case: item access for an object
934 # which is BOTH callable and implements __getitem__.
934 # which is BOTH callable and implements __getitem__.
935 newcmd = '%s %s' % (ifun,the_rest)
935 newcmd = '%s %s' % (ifun,the_rest)
936 auto_rewrite = False
936 auto_rewrite = False
937 else:
937 else:
938 # if the object doesn't support [] access, go ahead and
938 # if the object doesn't support [] access, go ahead and
939 # autocall
939 # autocall
940 newcmd = '%s(%s)' % (ifun.rstrip(),the_rest)
940 newcmd = '%s(%s)' % (ifun.rstrip(),the_rest)
941 elif the_rest.endswith(';'):
941 elif the_rest.endswith(';'):
942 newcmd = '%s(%s);' % (ifun.rstrip(),the_rest[:-1])
942 newcmd = '%s(%s);' % (ifun.rstrip(),the_rest[:-1])
943 else:
943 else:
944 newcmd = '%s(%s)' % (ifun.rstrip(), the_rest)
944 newcmd = '%s(%s)' % (ifun.rstrip(), the_rest)
945
945
946 if auto_rewrite:
946 if auto_rewrite:
947 rw = self.shell.outputcache.prompt1.auto_rewrite() + newcmd
947 rw = self.shell.outputcache.prompt1.auto_rewrite() + newcmd
948
948
949 try:
949 try:
950 # plain ascii works better w/ pyreadline, on some machines, so
950 # plain ascii works better w/ pyreadline, on some machines, so
951 # we use it and only print uncolored rewrite if we have unicode
951 # we use it and only print uncolored rewrite if we have unicode
952 rw = str(rw)
952 rw = str(rw)
953 print >>Term.cout, rw
953 print >>Term.cout, rw
954 except UnicodeEncodeError:
954 except UnicodeEncodeError:
955 print "-------------->" + newcmd
955 print "-------------->" + newcmd
956
956
957 # log what is now valid Python, not the actual user input (without the
957 # log what is now valid Python, not the actual user input (without the
958 # final newline)
958 # final newline)
959 self.shell.log(line,newcmd,continue_prompt)
959 self.shell.log(line,newcmd,continue_prompt)
960 return newcmd
960 return newcmd
961
961
962
962
963 class HelpHandler(PrefilterHandler):
963 class HelpHandler(PrefilterHandler):
964
964
965 handler_name = Str('help')
965 handler_name = Str('help')
966 esc_strings = List([ESC_HELP])
966 esc_strings = List([ESC_HELP])
967
967
968 def handle(self, line_info):
968 def handle(self, line_info):
969 """Try to get some help for the object.
969 """Try to get some help for the object.
970
970
971 obj? or ?obj -> basic information.
971 obj? or ?obj -> basic information.
972 obj?? or ??obj -> more details.
972 obj?? or ??obj -> more details.
973 """
973 """
974 normal_handler = self.prefilter_manager.get_handler_by_name('normal')
974 normal_handler = self.prefilter_manager.get_handler_by_name('normal')
975 line = line_info.line
975 line = line_info.line
976 # We need to make sure that we don't process lines which would be
976 # We need to make sure that we don't process lines which would be
977 # otherwise valid python, such as "x=1 # what?"
977 # otherwise valid python, such as "x=1 # what?"
978 try:
978 try:
979 codeop.compile_command(line)
979 codeop.compile_command(line)
980 except SyntaxError:
980 except SyntaxError:
981 # We should only handle as help stuff which is NOT valid syntax
981 # We should only handle as help stuff which is NOT valid syntax
982 if line[0]==ESC_HELP:
982 if line[0]==ESC_HELP:
983 line = line[1:]
983 line = line[1:]
984 elif line[-1]==ESC_HELP:
984 elif line[-1]==ESC_HELP:
985 line = line[:-1]
985 line = line[:-1]
986 self.shell.log(line, '#?'+line, line_info.continue_prompt)
986 self.shell.log(line, '#?'+line, line_info.continue_prompt)
987 if line:
987 if line:
988 #print 'line:<%r>' % line # dbg
988 #print 'line:<%r>' % line # dbg
989 self.shell.magic_pinfo(line)
989 self.shell.magic_pinfo(line)
990 else:
990 else:
991 page(self.shell.usage, screen_lines=self.shell.usable_screen_length)
991 page(self.shell.usage, screen_lines=self.shell.usable_screen_length)
992 return '' # Empty string is needed here!
992 return '' # Empty string is needed here!
993 except:
993 except:
994 raise
994 raise
995 # Pass any other exceptions through to the normal handler
995 # Pass any other exceptions through to the normal handler
996 return normal_handler.handle(line_info)
996 return normal_handler.handle(line_info)
997 else:
997 else:
998 raise
999 # If the code compiles ok, we should handle it normally
998 # If the code compiles ok, we should handle it normally
1000 return normal_handler.handle(line_info)
999 return normal_handler.handle(line_info)
1001
1000
1002
1001
1003 class EmacsHandler(PrefilterHandler):
1002 class EmacsHandler(PrefilterHandler):
1004
1003
1005 handler_name = Str('emacs')
1004 handler_name = Str('emacs')
1006 esc_strings = List([])
1005 esc_strings = List([])
1007
1006
1008 def handle(self, line_info):
1007 def handle(self, line_info):
1009 """Handle input lines marked by python-mode."""
1008 """Handle input lines marked by python-mode."""
1010
1009
1011 # Currently, nothing is done. Later more functionality can be added
1010 # Currently, nothing is done. Later more functionality can be added
1012 # here if needed.
1011 # here if needed.
1013
1012
1014 # The input cache shouldn't be updated
1013 # The input cache shouldn't be updated
1015 return line_info.line
1014 return line_info.line
1016
1015
1017
1016
1018 #-----------------------------------------------------------------------------
1017 #-----------------------------------------------------------------------------
1019 # Defaults
1018 # Defaults
1020 #-----------------------------------------------------------------------------
1019 #-----------------------------------------------------------------------------
1021
1020
1022
1021
1023 _default_transformers = [
1022 _default_transformers = [
1024 AssignSystemTransformer,
1023 AssignSystemTransformer,
1025 AssignMagicTransformer,
1024 AssignMagicTransformer,
1026 PyPromptTransformer,
1025 PyPromptTransformer,
1027 IPyPromptTransformer,
1026 IPyPromptTransformer,
1028 ]
1027 ]
1029
1028
1030 _default_checkers = [
1029 _default_checkers = [
1031 EmacsChecker,
1030 EmacsChecker,
1032 ShellEscapeChecker,
1031 ShellEscapeChecker,
1033 IPyAutocallChecker,
1032 IPyAutocallChecker,
1034 MultiLineMagicChecker,
1033 MultiLineMagicChecker,
1035 EscCharsChecker,
1034 EscCharsChecker,
1036 AssignmentChecker,
1035 AssignmentChecker,
1037 AutoMagicChecker,
1036 AutoMagicChecker,
1038 AliasChecker,
1037 AliasChecker,
1039 PythonOpsChecker,
1038 PythonOpsChecker,
1040 AutocallChecker
1039 AutocallChecker
1041 ]
1040 ]
1042
1041
1043 _default_handlers = [
1042 _default_handlers = [
1044 PrefilterHandler,
1043 PrefilterHandler,
1045 AliasHandler,
1044 AliasHandler,
1046 ShellEscapeHandler,
1045 ShellEscapeHandler,
1047 MagicHandler,
1046 MagicHandler,
1048 AutoHandler,
1047 AutoHandler,
1049 HelpHandler,
1048 HelpHandler,
1050 EmacsHandler
1049 EmacsHandler
1051 ]
1050 ]
@@ -1,202 +1,174 b''
1 """Test the various handlers which do the actual rewriting of the line."""
1 """Tests for input handlers.
2 """
3 #-----------------------------------------------------------------------------
4 # Module imports
5 #-----------------------------------------------------------------------------
2
6
3 from StringIO import StringIO
7 # third party
4 import sys
8 import nose.tools as nt
5 sys.path.append('..')
9
10 # our own packages
11 from IPython.core import autocall
12 from IPython.testing import decorators as dec
13 from IPython.testing.globalipapp import get_ipython
14
15 #-----------------------------------------------------------------------------
16 # Globals
17 #-----------------------------------------------------------------------------
18
19 # Get the public instance of IPython
20 ip = get_ipython()
6
21
7 failures = []
22 failures = []
8 num_tests = 0
23 num_tests = 0
9
24
25 #-----------------------------------------------------------------------------
26 # Test functions
27 #-----------------------------------------------------------------------------
28
29 class CallableIndexable(object):
30 def __getitem__(self, idx): return True
31 def __call__(self, *args, **kws): return True
32
33
34 class Autocallable(autocall.IPyAutocall):
35 def __call__(self):
36 return "called"
37
38
10 def run(tests):
39 def run(tests):
11 """Loop through a list of (pre, post) inputs, where pre is the string
40 """Loop through a list of (pre, post) inputs, where pre is the string
12 handed to ipython, and post is how that string looks after it's been
41 handed to ipython, and post is how that string looks after it's been
13 transformed (i.e. ipython's notion of _i)"""
42 transformed (i.e. ipython's notion of _i)"""
14 for pre, post in tests:
43 for pre, post in tests:
15 global num_tests
44 global num_tests
16 num_tests += 1
45 num_tests += 1
17 ip.runlines(pre)
46 ip.runlines(pre)
18 ip.runlines('_i') # Not sure why I need this...
47 ip.runlines('_i') # Not sure why I need this...
19 actual = ip.user_ns['_i']
48 actual = ip.user_ns['_i']
20 if actual != None:
49 if actual != None:
21 actual = actual.rstrip('\n')
50 actual = actual.rstrip('\n')
22 if actual != post:
51 if actual != post:
23 failures.append('Expected %r to become %r, found %r' % (
52 failures.append('Expected %r to become %r, found %r' % (
24 pre, post, actual))
53 pre, post, actual))
25
54
26
55
27 # Shutdown stdout/stderr so that ipython isn't noisy during tests. Have to
56 def test_handlers():
28 # do this *before* importing IPython below.
29 #
30 # NOTE: this means that, if you stick print statements into code as part of
31 # debugging, you won't see the results (unless you comment out some of the
32 # below). I keep on doing this, so apparently it's easy. Or I am an idiot.
33 old_stdout = sys.stdout
34 old_stderr = sys.stderr
35
36 sys.stdout = StringIO()
37 sys.stderr = StringIO()
38
39 import IPython
40 import IPython.ipapi
41
42 IPython.Shell.start()
43 ip = IPython.ipapi.get()
44
45 class CallableIndexable(object):
46 def __getitem__(self, idx): return True
47 def __call__(self, *args, **kws): return True
48
49
50 try:
51 # alias expansion
57 # alias expansion
52
58
53 # We're using 'true' as our syscall of choice because it doesn't
59 # We're using 'true' as our syscall of choice because it doesn't
54 # write anything to stdout.
60 # write anything to stdout.
55
61
56 # Turn off actual execution of aliases, because it's noisy
62 # Turn off actual execution of aliases, because it's noisy
57 old_system_cmd = ip.system
63 old_system_cmd = ip.system
58 ip.system = lambda cmd: None
64 ip.system = lambda cmd: None
59
65
60
66
61 ip.IP.alias_table['an_alias'] = (0, 'true')
67 ip.alias_manager.alias_table['an_alias'] = (0, 'true')
62 # These are useful for checking a particular recursive alias issue
68 # These are useful for checking a particular recursive alias issue
63 ip.IP.alias_table['top'] = (0, 'd:/cygwin/top')
69 ip.alias_manager.alias_table['top'] = (0, 'd:/cygwin/top')
64 ip.IP.alias_table['d'] = (0, 'true')
70 ip.alias_manager.alias_table['d'] = (0, 'true')
65 run([("an_alias", '_ip.system("true ")'), # alias
71 run([("an_alias", 'get_ipython().system("true ")'), # alias
66 # Below: recursive aliases should expand whitespace-surrounded
72 # Below: recursive aliases should expand whitespace-surrounded
67 # chars, *not* initial chars which happen to be aliases:
73 # chars, *not* initial chars which happen to be aliases:
68 ("top", '_ip.system("d:/cygwin/top ")'),
74 ("top", 'get_ipython().system("d:/cygwin/top ")'),
69 ])
75 ])
70 ip.system = old_system_cmd
76 ip.system = old_system_cmd
71
77
72
73 call_idx = CallableIndexable()
78 call_idx = CallableIndexable()
74 ip.to_user_ns('call_idx')
79 ip.user_ns['call_idx'] = call_idx
75
80
76 # For many of the below, we're also checking that leading whitespace
81 # For many of the below, we're also checking that leading whitespace
77 # turns off the esc char, which it should unless there is a continuation
82 # turns off the esc char, which it should unless there is a continuation
78 # line.
83 # line.
79 run([('"no change"', '"no change"'), # normal
84 run([('"no change"', '"no change"'), # normal
80 ("!true", '_ip.system("true")'), # shell_escapes
85 ("!true", 'get_ipython().system("true")'), # shell_escapes
81 ("!! true", '_ip.magic("sx true")'), # shell_escapes + magic
86 ("!! true", 'get_ipython().magic("sx true")'), # shell_escapes + magic
82 ("!!true", '_ip.magic("sx true")'), # shell_escapes + magic
87 ("!!true", 'get_ipython().magic("sx true")'), # shell_escapes + magic
83 ("%lsmagic", '_ip.magic("lsmagic ")'), # magic
88 ("%lsmagic", 'get_ipython().magic("lsmagic ")'), # magic
84 ("lsmagic", '_ip.magic("lsmagic ")'), # magic
89 ("lsmagic", 'get_ipython().magic("lsmagic ")'), # magic
85 ("a = b # PYTHON-MODE", '_i'), # emacs -- avoids _in cache
90 #("a = b # PYTHON-MODE", '_i'), # emacs -- avoids _in cache
86
91
87 # post-esc-char whitespace goes inside
92 # post-esc-char whitespace goes inside
88 ("! true", '_ip.system(" true")'),
93 ("! true", 'get_ipython().system(" true")'),
89
90 # Leading whitespace generally turns off escape characters
91 (" ! true", ' ! true'),
92 (" !true", ' !true'),
93
94
94 # handle_help
95 # handle_help
95
96
96 # These are weak tests -- just looking at what the help handlers
97 # These are weak tests -- just looking at what the help handlers
97 # logs, which is not how it really does its work. But it still
98 # logs, which is not how it really does its work. But it still
98 # lets us check the key paths through the handler.
99 # lets us check the key paths through the handler.
99
100
100 ("x=1 # what?", "x=1 # what?"), # no help if valid python
101 ("x=1 # what?", "x=1 # what?"), # no help if valid python
101 ("len?", "#?len"), # this is what help logs when it runs
102 ("len??", "#?len?"),
103 ("?len", "#?len"),
104 ])
102 ])
105
103
106 # multi_line_specials
104 # multi_line_specials
107 ip.options.multi_line_specials = 0
105 ip.prefilter_manager.multi_line_specials = False
108 # W/ multi_line_specials off, leading ws kills esc chars/autoexpansion
106 # W/ multi_line_specials off, leading ws kills esc chars/autoexpansion
109 run([
107 run([
110 ('if 1:\n !true', 'if 1:\n !true'),
108 ('if 1:\n !true', 'if 1:\n !true'),
111 ('if 1:\n lsmagic', 'if 1:\n lsmagic'),
109 ('if 1:\n lsmagic', 'if 1:\n lsmagic'),
112 ('if 1:\n an_alias', 'if 1:\n an_alias'),
110 ('if 1:\n an_alias', 'if 1:\n an_alias'),
113 ])
111 ])
114
112
115 ip.options.multi_line_specials = 1
113 ip.prefilter_manager.multi_line_specials = True
116 # initial indents must be preserved.
114 # initial indents must be preserved.
117 run([
115 run([
118 ('if 1:\n !true', 'if 1:\n _ip.system("true")'),
116 ('if 1:\n !true', 'if 1:\n get_ipython().system("true")'),
119 ('if 1:\n lsmagic', 'if 1:\n _ip.magic("lsmagic ")'),
117 ('if 2:\n lsmagic', 'if 2:\n get_ipython().magic("lsmagic ")'),
120 ('if 1:\n an_alias', 'if 1:\n _ip.system("true ")'),
118 ('if 1:\n an_alias', 'if 1:\n get_ipython().system("true ")'),
121 # Weird one
119 # Weird one
122 ('if 1:\n !!true', 'if 1:\n _ip.magic("sx true")'),
120 ('if 1:\n !!true', 'if 1:\n get_ipython().magic("sx true")'),
123
124
121
125 # Even with m_l_s on, all esc_chars except ! are off
122 # Even with m_l_s on, autocall is off even with special chars
126 ('if 1:\n %lsmagic', 'if 1:\n %lsmagic'),
127 ('if 1:\n /fun 1 2', 'if 1:\n /fun 1 2'),
123 ('if 1:\n /fun 1 2', 'if 1:\n /fun 1 2'),
128 ('if 1:\n ;fun 1 2', 'if 1:\n ;fun 1 2'),
124 ('if 1:\n ;fun 1 2', 'if 1:\n ;fun 1 2'),
129 ('if 1:\n ,fun 1 2', 'if 1:\n ,fun 1 2'),
125 ('if 1:\n ,fun 1 2', 'if 1:\n ,fun 1 2'),
130 ('if 1:\n ?fun 1 2', 'if 1:\n ?fun 1 2'),
126 ('if 1:\n ?fun 1 2', 'if 1:\n ?fun 1 2'),
131 # What about !!
127 # What about !!
132 ])
128 ])
133
129
134
135 # Objects which are instances of IPyAutocall are *always* autocalled
130 # Objects which are instances of IPyAutocall are *always* autocalled
136 import IPython.ipapi
137 class Autocallable(IPython.ipapi.IPyAutocall):
138 def __call__(self):
139 return "called"
140
141 autocallable = Autocallable()
131 autocallable = Autocallable()
142 ip.to_user_ns('autocallable')
132 ip.user_ns['autocallable'] = autocallable
143
133
144 # auto
134 # auto
145 ip.options.autocall = 0
135 ip.magic('autocall 0')
146 # Only explicit escapes or instances of IPyAutocallable should get
136 # Only explicit escapes or instances of IPyAutocallable should get
147 # expanded
137 # expanded
148 run([
138 run([
149 ('len "abc"', 'len "abc"'),
139 ('len "abc"', 'len "abc"'),
150 ('autocallable', 'autocallable()'),
140 ('autocallable', 'autocallable()'),
151 (",list 1 2 3", 'list("1", "2", "3")'),
141 (",list 1 2 3", 'list("1", "2", "3")'),
152 (";list 1 2 3", 'list("1 2 3")'),
142 (";list 1 2 3", 'list("1 2 3")'),
153 ("/len range(1,4)", 'len(range(1,4))'),
143 ("/len range(1,4)", 'len(range(1,4))'),
154 ])
144 ])
155 ip.options.autocall = 1
145 ip.magic('autocall 1')
156 run([
146 run([
157 (",list 1 2 3", 'list("1", "2", "3")'),
147 (",list 1 2 3", 'list("1", "2", "3")'),
158 (";list 1 2 3", 'list("1 2 3")'),
148 (";list 1 2 3", 'list("1 2 3")'),
159 ("/len range(1,4)", 'len(range(1,4))'),
149 ("/len range(1,4)", 'len(range(1,4))'),
160 ('len "abc"', 'len("abc")'),
150 ('len "abc"', 'len("abc")'),
161 ('len "abc";', 'len("abc");'), # ; is special -- moves out of parens
151 ('len "abc";', 'len("abc");'), # ; is special -- moves out of parens
162 # Autocall is turned off if first arg is [] and the object
152 # Autocall is turned off if first arg is [] and the object
163 # is both callable and indexable. Like so:
153 # is both callable and indexable. Like so:
164 ('len [1,2]', 'len([1,2])'), # len doesn't support __getitem__...
154 ('len [1,2]', 'len([1,2])'), # len doesn't support __getitem__...
165 ('call_idx [1]', 'call_idx [1]'), # call_idx *does*..
155 ('call_idx [1]', 'call_idx [1]'), # call_idx *does*..
166 ('call_idx 1', 'call_idx(1)'),
156 ('call_idx 1', 'call_idx(1)'),
167 ('len', 'len '), # only at 2 does it auto-call on single args
157 ('len', 'len '), # only at 2 does it auto-call on single args
168 ])
158 ])
169
159 ip.magic('autocall 2')
170 ip.options.autocall = 2
171 run([
160 run([
172 (",list 1 2 3", 'list("1", "2", "3")'),
161 (",list 1 2 3", 'list("1", "2", "3")'),
173 (";list 1 2 3", 'list("1 2 3")'),
162 (";list 1 2 3", 'list("1 2 3")'),
174 ("/len range(1,4)", 'len(range(1,4))'),
163 ("/len range(1,4)", 'len(range(1,4))'),
175 ('len "abc"', 'len("abc")'),
164 ('len "abc"', 'len("abc")'),
176 ('len "abc";', 'len("abc");'),
165 ('len "abc";', 'len("abc");'),
177 ('len [1,2]', 'len([1,2])'),
166 ('len [1,2]', 'len([1,2])'),
178 ('call_idx [1]', 'call_idx [1]'),
167 ('call_idx [1]', 'call_idx [1]'),
179 ('call_idx 1', 'call_idx(1)'),
168 ('call_idx 1', 'call_idx(1)'),
180 # This is what's different:
169 # This is what's different:
181 ('len', 'len()'), # only at 2 does it auto-call on single args
170 ('len', 'len()'), # only at 2 does it auto-call on single args
182 ])
171 ])
183 ip.options.autocall = 1
172 ip.magic('autocall 1')
184
185 # Ignoring handle_emacs, 'cause it doesn't do anything.
186 finally:
187 sys.stdout = old_stdout
188 sys.stderr = old_stderr
189
190
191
192
193 num_f = len(failures)
194 #if verbose:
195 # print
196
197
173
198 print "%s tests run, %s failure%s" % (num_tests,
174 nt.assert_equals(failures, [])
199 num_f,
200 num_f != 1 and "s" or "")
201 for f in failures:
202 print f
@@ -1,245 +1,279 b''
1 """Tests for the key iplib module, where the main ipython class is defined.
1 """Tests for the key iplib module, where the main ipython class is defined.
2 """
2 """
3 #-----------------------------------------------------------------------------
3 #-----------------------------------------------------------------------------
4 # Module imports
4 # Module imports
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6
6
7 # stdlib
7 # stdlib
8 import os
8 import os
9 import shutil
9 import shutil
10 import tempfile
10 import tempfile
11
11
12 # third party
12 # third party
13 import nose.tools as nt
13 import nose.tools as nt
14
14
15 # our own packages
15 # our own packages
16 from IPython.testing import decorators as dec
16 from IPython.testing import decorators as dec
17 from IPython.testing.globalipapp import get_ipython
17 from IPython.testing.globalipapp import get_ipython
18
18
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20 # Globals
20 # Globals
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22
22
23 # Get the public instance of IPython
23 # Get the public instance of IPython
24 ip = get_ipython()
24 ip = get_ipython()
25
25
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27 # Test functions
27 # Test functions
28 #-----------------------------------------------------------------------------
28 #-----------------------------------------------------------------------------
29
29
30 @dec.parametric
30 @dec.parametric
31 def test_reset():
31 def test_reset():
32 """reset must clear most namespaces."""
32 """reset must clear most namespaces."""
33 # The number of variables in the private user_ns_hidden is not zero, but it
33 # The number of variables in the private user_ns_hidden is not zero, but it
34 # should be constant regardless of what we do
34 # should be constant regardless of what we do
35 nvars_config_ns = len(ip.user_ns_hidden)
35 nvars_config_ns = len(ip.user_ns_hidden)
36
36
37 # Check that reset runs without error
37 # Check that reset runs without error
38 ip.reset()
38 ip.reset()
39
39
40 # Once we've reset it (to clear of any junk that might have been there from
40 # Once we've reset it (to clear of any junk that might have been there from
41 # other tests, we can count how many variables are in the user's namespace
41 # other tests, we can count how many variables are in the user's namespace
42 nvars_user_ns = len(ip.user_ns)
42 nvars_user_ns = len(ip.user_ns)
43
43
44 # Now add a few variables to user_ns, and check that reset clears them
44 # Now add a few variables to user_ns, and check that reset clears them
45 ip.user_ns['x'] = 1
45 ip.user_ns['x'] = 1
46 ip.user_ns['y'] = 1
46 ip.user_ns['y'] = 1
47 ip.reset()
47 ip.reset()
48
48
49 # Finally, check that all namespaces have only as many variables as we
49 # Finally, check that all namespaces have only as many variables as we
50 # expect to find in them:
50 # expect to find in them:
51 for ns in ip.ns_refs_table:
51 for ns in ip.ns_refs_table:
52 if ns is ip.user_ns:
52 if ns is ip.user_ns:
53 nvars_expected = nvars_user_ns
53 nvars_expected = nvars_user_ns
54 elif ns is ip.user_ns_hidden:
54 elif ns is ip.user_ns_hidden:
55 nvars_expected = nvars_config_ns
55 nvars_expected = nvars_config_ns
56 else:
56 else:
57 nvars_expected = 0
57 nvars_expected = 0
58
58
59 yield nt.assert_equals(len(ns), nvars_expected)
59 yield nt.assert_equals(len(ns), nvars_expected)
60
60
61
61
62 # Tests for reporting of exceptions in various modes, handling of SystemExit,
62 # Tests for reporting of exceptions in various modes, handling of SystemExit,
63 # and %tb functionality. This is really a mix of testing ultraTB and iplib.
63 # and %tb functionality. This is really a mix of testing ultraTB and iplib.
64
64
65 def doctest_tb_plain():
65 def doctest_tb_plain():
66 """
66 """
67 In [18]: xmode plain
67 In [18]: xmode plain
68 Exception reporting mode: Plain
68 Exception reporting mode: Plain
69
69
70 In [19]: run simpleerr.py
70 In [19]: run simpleerr.py
71 Traceback (most recent call last):
71 Traceback (most recent call last):
72 ...line 32, in <module>
72 ...line 32, in <module>
73 bar(mode)
73 bar(mode)
74 ...line 16, in bar
74 ...line 16, in bar
75 div0()
75 div0()
76 ...line 8, in div0
76 ...line 8, in div0
77 x/y
77 x/y
78 ZeroDivisionError: integer division or modulo by zero
78 ZeroDivisionError: integer division or modulo by zero
79 """
79 """
80
80
81
81
82 def doctest_tb_context():
82 def doctest_tb_context():
83 """
83 """
84 In [3]: xmode context
84 In [3]: xmode context
85 Exception reporting mode: Context
85 Exception reporting mode: Context
86
86
87 In [4]: run simpleerr.py
87 In [4]: run simpleerr.py
88 ---------------------------------------------------------------------------
88 ---------------------------------------------------------------------------
89 ZeroDivisionError Traceback (most recent call last)
89 ZeroDivisionError Traceback (most recent call last)
90 <BLANKLINE>
90 <BLANKLINE>
91 ... in <module>()
91 ... in <module>()
92 30 mode = 'div'
92 30 mode = 'div'
93 31
93 31
94 ---> 32 bar(mode)
94 ---> 32 bar(mode)
95 33
95 33
96 34
96 34
97 <BLANKLINE>
97 <BLANKLINE>
98 ... in bar(mode)
98 ... in bar(mode)
99 14 "bar"
99 14 "bar"
100 15 if mode=='div':
100 15 if mode=='div':
101 ---> 16 div0()
101 ---> 16 div0()
102 17 elif mode=='exit':
102 17 elif mode=='exit':
103 18 try:
103 18 try:
104 <BLANKLINE>
104 <BLANKLINE>
105 ... in div0()
105 ... in div0()
106 6 x = 1
106 6 x = 1
107 7 y = 0
107 7 y = 0
108 ----> 8 x/y
108 ----> 8 x/y
109 9
109 9
110 10 def sysexit(stat, mode):
110 10 def sysexit(stat, mode):
111 <BLANKLINE>
111 <BLANKLINE>
112 ZeroDivisionError: integer division or modulo by zero
112 ZeroDivisionError: integer division or modulo by zero
113 """
113 """
114
114
115
115
116 def doctest_tb_verbose():
116 def doctest_tb_verbose():
117 """
117 """
118 In [5]: xmode verbose
118 In [5]: xmode verbose
119 Exception reporting mode: Verbose
119 Exception reporting mode: Verbose
120
120
121 In [6]: run simpleerr.py
121 In [6]: run simpleerr.py
122 ---------------------------------------------------------------------------
122 ---------------------------------------------------------------------------
123 ZeroDivisionError Traceback (most recent call last)
123 ZeroDivisionError Traceback (most recent call last)
124 <BLANKLINE>
124 <BLANKLINE>
125 ... in <module>()
125 ... in <module>()
126 30 mode = 'div'
126 30 mode = 'div'
127 31
127 31
128 ---> 32 bar(mode)
128 ---> 32 bar(mode)
129 global bar = <function bar at ...>
129 global bar = <function bar at ...>
130 global mode = 'div'
130 global mode = 'div'
131 33
131 33
132 34
132 34
133 <BLANKLINE>
133 <BLANKLINE>
134 ... in bar(mode='div')
134 ... in bar(mode='div')
135 14 "bar"
135 14 "bar"
136 15 if mode=='div':
136 15 if mode=='div':
137 ---> 16 div0()
137 ---> 16 div0()
138 global div0 = <function div0 at ...>
138 global div0 = <function div0 at ...>
139 17 elif mode=='exit':
139 17 elif mode=='exit':
140 18 try:
140 18 try:
141 <BLANKLINE>
141 <BLANKLINE>
142 ... in div0()
142 ... in div0()
143 6 x = 1
143 6 x = 1
144 7 y = 0
144 7 y = 0
145 ----> 8 x/y
145 ----> 8 x/y
146 x = 1
146 x = 1
147 y = 0
147 y = 0
148 9
148 9
149 10 def sysexit(stat, mode):
149 10 def sysexit(stat, mode):
150 <BLANKLINE>
150 <BLANKLINE>
151 ZeroDivisionError: integer division or modulo by zero
151 ZeroDivisionError: integer division or modulo by zero
152 """
152 """
153
153
154
154
155 def doctest_tb_sysexit():
155 def doctest_tb_sysexit():
156 """
156 """
157 In [17]: %xmode plain
157 In [17]: %xmode plain
158 Exception reporting mode: Plain
158 Exception reporting mode: Plain
159
159
160 In [18]: %run simpleerr.py exit
160 In [18]: %run simpleerr.py exit
161 An exception has occurred, use %tb to see the full traceback.
161 An exception has occurred, use %tb to see the full traceback.
162 SystemExit: (1, 'Mode = exit')
162 SystemExit: (1, 'Mode = exit')
163
163
164 In [19]: %run simpleerr.py exit 2
164 In [19]: %run simpleerr.py exit 2
165 An exception has occurred, use %tb to see the full traceback.
165 An exception has occurred, use %tb to see the full traceback.
166 SystemExit: (2, 'Mode = exit')
166 SystemExit: (2, 'Mode = exit')
167
167
168 In [20]: %tb
168 In [20]: %tb
169 Traceback (most recent call last):
169 Traceback (most recent call last):
170 File ... in <module>
170 File ... in <module>
171 bar(mode)
171 bar(mode)
172 File ... line 22, in bar
172 File ... line 22, in bar
173 sysexit(stat, mode)
173 sysexit(stat, mode)
174 File ... line 11, in sysexit
174 File ... line 11, in sysexit
175 raise SystemExit(stat, 'Mode = %s' % mode)
175 raise SystemExit(stat, 'Mode = %s' % mode)
176 SystemExit: (2, 'Mode = exit')
176 SystemExit: (2, 'Mode = exit')
177
177
178 In [21]: %xmode context
178 In [21]: %xmode context
179 Exception reporting mode: Context
179 Exception reporting mode: Context
180
180
181 In [22]: %tb
181 In [22]: %tb
182 ---------------------------------------------------------------------------
182 ---------------------------------------------------------------------------
183 SystemExit Traceback (most recent call last)
183 SystemExit Traceback (most recent call last)
184 <BLANKLINE>
184 <BLANKLINE>
185 ...<module>()
185 ...<module>()
186 30 mode = 'div'
186 30 mode = 'div'
187 31
187 31
188 ---> 32 bar(mode)
188 ---> 32 bar(mode)
189 33
189 33
190 34
190 34
191 <BLANKLINE>
191 <BLANKLINE>
192 ...bar(mode)
192 ...bar(mode)
193 20 except:
193 20 except:
194 21 stat = 1
194 21 stat = 1
195 ---> 22 sysexit(stat, mode)
195 ---> 22 sysexit(stat, mode)
196 23 else:
196 23 else:
197 24 raise ValueError('Unknown mode')
197 24 raise ValueError('Unknown mode')
198 <BLANKLINE>
198 <BLANKLINE>
199 ...sysexit(stat, mode)
199 ...sysexit(stat, mode)
200 9
200 9
201 10 def sysexit(stat, mode):
201 10 def sysexit(stat, mode):
202 ---> 11 raise SystemExit(stat, 'Mode = %s' % mode)
202 ---> 11 raise SystemExit(stat, 'Mode = %s' % mode)
203 12
203 12
204 13 def bar(mode):
204 13 def bar(mode):
205 <BLANKLINE>
205 <BLANKLINE>
206 SystemExit: (2, 'Mode = exit')
206 SystemExit: (2, 'Mode = exit')
207
207
208 In [23]: %xmode verbose
208 In [23]: %xmode verbose
209 Exception reporting mode: Verbose
209 Exception reporting mode: Verbose
210
210
211 In [24]: %tb
211 In [24]: %tb
212 ---------------------------------------------------------------------------
212 ---------------------------------------------------------------------------
213 SystemExit Traceback (most recent call last)
213 SystemExit Traceback (most recent call last)
214 <BLANKLINE>
214 <BLANKLINE>
215 ... in <module>()
215 ... in <module>()
216 30 mode = 'div'
216 30 mode = 'div'
217 31
217 31
218 ---> 32 bar(mode)
218 ---> 32 bar(mode)
219 global bar = <function bar at ...>
219 global bar = <function bar at ...>
220 global mode = 'exit'
220 global mode = 'exit'
221 33
221 33
222 34
222 34
223 <BLANKLINE>
223 <BLANKLINE>
224 ... in bar(mode='exit')
224 ... in bar(mode='exit')
225 20 except:
225 20 except:
226 21 stat = 1
226 21 stat = 1
227 ---> 22 sysexit(stat, mode)
227 ---> 22 sysexit(stat, mode)
228 global sysexit = <function sysexit at ...>
228 global sysexit = <function sysexit at ...>
229 stat = 2
229 stat = 2
230 mode = 'exit'
230 mode = 'exit'
231 23 else:
231 23 else:
232 24 raise ValueError('Unknown mode')
232 24 raise ValueError('Unknown mode')
233 <BLANKLINE>
233 <BLANKLINE>
234 ... in sysexit(stat=2, mode='exit')
234 ... in sysexit(stat=2, mode='exit')
235 9
235 9
236 10 def sysexit(stat, mode):
236 10 def sysexit(stat, mode):
237 ---> 11 raise SystemExit(stat, 'Mode = %s' % mode)
237 ---> 11 raise SystemExit(stat, 'Mode = %s' % mode)
238 global SystemExit = undefined
238 global SystemExit = undefined
239 stat = 2
239 stat = 2
240 mode = 'exit'
240 mode = 'exit'
241 12
241 12
242 13 def bar(mode):
242 13 def bar(mode):
243 <BLANKLINE>
243 <BLANKLINE>
244 SystemExit: (2, 'Mode = exit')
244 SystemExit: (2, 'Mode = exit')
245 """
245 """
246
247
248 def test_runlines():
249 import textwrap
250 ip.runlines(['a = 10', 'a+=1'])
251 ip.runlines('assert a == 11\nassert 1')
252
253 nt.assert_equals(ip.user_ns['a'], 11)
254 complex = textwrap.dedent("""
255 if 1:
256 print "hello"
257 if 1:
258 print "world"
259
260 if 2:
261 print "foo"
262
263 if 3:
264 print "bar"
265
266 if 4:
267 print "bar"
268
269 """)
270 # Simply verifies that this kind of input is run
271 ip.runlines(complex)
272
273
274 def test_db():
275 """Test the internal database used for variable persistence."""
276 ip.db['__unittest_'] = 12
277 nt.assert_equals(ip.db['__unittest_'], 12)
278 del ip.db['__unittest_']
279 assert '__unittest_' not in ip.db
@@ -1,274 +1,357 b''
1 """Tests for various magic functions.
1 """Tests for various magic functions.
2
2
3 Needs to be run by nose (to make ipython session available).
3 Needs to be run by nose (to make ipython session available).
4 """
4 """
5 from __future__ import absolute_import
5 from __future__ import absolute_import
6
6
7 #-----------------------------------------------------------------------------
7 #-----------------------------------------------------------------------------
8 # Imports
8 # Imports
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10
10
11 import os
11 import os
12 import sys
12 import sys
13 import tempfile
13 import tempfile
14 import types
14 import types
15 from cStringIO import StringIO
15 from cStringIO import StringIO
16
16
17 import nose.tools as nt
17 import nose.tools as nt
18
18
19 from IPython.utils.path import get_long_path_name
19 from IPython.utils.path import get_long_path_name
20 from IPython.testing import decorators as dec
20 from IPython.testing import decorators as dec
21 from IPython.testing import tools as tt
21 from IPython.testing import tools as tt
22
22
23 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
24 # Test functions begin
24 # Test functions begin
25 #-----------------------------------------------------------------------------
25 #-----------------------------------------------------------------------------
26 def test_rehashx():
26 def test_rehashx():
27 # clear up everything
27 # clear up everything
28 _ip = get_ipython()
28 _ip = get_ipython()
29 _ip.alias_manager.alias_table.clear()
29 _ip.alias_manager.alias_table.clear()
30 del _ip.db['syscmdlist']
30 del _ip.db['syscmdlist']
31
31
32 _ip.magic('rehashx')
32 _ip.magic('rehashx')
33 # Practically ALL ipython development systems will have more than 10 aliases
33 # Practically ALL ipython development systems will have more than 10 aliases
34
34
35 yield (nt.assert_true, len(_ip.alias_manager.alias_table) > 10)
35 yield (nt.assert_true, len(_ip.alias_manager.alias_table) > 10)
36 for key, val in _ip.alias_manager.alias_table.items():
36 for key, val in _ip.alias_manager.alias_table.items():
37 # we must strip dots from alias names
37 # we must strip dots from alias names
38 nt.assert_true('.' not in key)
38 nt.assert_true('.' not in key)
39
39
40 # rehashx must fill up syscmdlist
40 # rehashx must fill up syscmdlist
41 scoms = _ip.db['syscmdlist']
41 scoms = _ip.db['syscmdlist']
42 yield (nt.assert_true, len(scoms) > 10)
42 yield (nt.assert_true, len(scoms) > 10)
43
43
44
44
45 def test_magic_parse_options():
45 def test_magic_parse_options():
46 """Test that we don't mangle paths when parsing magic options."""
46 """Test that we don't mangle paths when parsing magic options."""
47 ip = get_ipython()
47 ip = get_ipython()
48 path = 'c:\\x'
48 path = 'c:\\x'
49 opts = ip.parse_options('-f %s' % path,'f:')[0]
49 opts = ip.parse_options('-f %s' % path,'f:')[0]
50 # argv splitting is os-dependent
50 # argv splitting is os-dependent
51 if os.name == 'posix':
51 if os.name == 'posix':
52 expected = 'c:x'
52 expected = 'c:x'
53 else:
53 else:
54 expected = path
54 expected = path
55 nt.assert_equals(opts['f'], expected)
55 nt.assert_equals(opts['f'], expected)
56
56
57
57
58 def doctest_hist_f():
58 def doctest_hist_f():
59 """Test %hist -f with temporary filename.
59 """Test %hist -f with temporary filename.
60
60
61 In [9]: import tempfile
61 In [9]: import tempfile
62
62
63 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
63 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
64
64
65 In [11]: %hist -n -f $tfile 3
65 In [11]: %hist -n -f $tfile 3
66
66
67 In [13]: import os; os.unlink(tfile)
67 In [13]: import os; os.unlink(tfile)
68 """
68 """
69
69
70
70
71 def doctest_hist_r():
71 def doctest_hist_r():
72 """Test %hist -r
72 """Test %hist -r
73
73
74 XXX - This test is not recording the output correctly. For some reason, in
74 XXX - This test is not recording the output correctly. For some reason, in
75 testing mode the raw history isn't getting populated. No idea why.
75 testing mode the raw history isn't getting populated. No idea why.
76 Disabling the output checking for now, though at least we do run it.
76 Disabling the output checking for now, though at least we do run it.
77
77
78 In [1]: 'hist' in _ip.lsmagic()
78 In [1]: 'hist' in _ip.lsmagic()
79 Out[1]: True
79 Out[1]: True
80
80
81 In [2]: x=1
81 In [2]: x=1
82
82
83 In [3]: %hist -r 2
83 In [3]: %hist -r 2
84 x=1 # random
84 x=1 # random
85 %hist -r 2
85 %hist -r 2
86 """
86 """
87
87
88 def doctest_hist_op():
88 def doctest_hist_op():
89 """Test %hist -op
89 """Test %hist -op
90
90
91 In [1]: class b:
91 In [1]: class b:
92 ...: pass
92 ...: pass
93 ...:
93 ...:
94
94
95 In [2]: class s(b):
95 In [2]: class s(b):
96 ...: def __str__(self):
96 ...: def __str__(self):
97 ...: return 's'
97 ...: return 's'
98 ...:
98 ...:
99
99
100 In [3]:
100 In [3]:
101
101
102 In [4]: class r(b):
102 In [4]: class r(b):
103 ...: def __repr__(self):
103 ...: def __repr__(self):
104 ...: return 'r'
104 ...: return 'r'
105 ...:
105 ...:
106
106
107 In [5]: class sr(s,r): pass
107 In [5]: class sr(s,r): pass
108 ...:
108 ...:
109
109
110 In [6]:
110 In [6]:
111
111
112 In [7]: bb=b()
112 In [7]: bb=b()
113
113
114 In [8]: ss=s()
114 In [8]: ss=s()
115
115
116 In [9]: rr=r()
116 In [9]: rr=r()
117
117
118 In [10]: ssrr=sr()
118 In [10]: ssrr=sr()
119
119
120 In [11]: bb
120 In [11]: bb
121 Out[11]: <...b instance at ...>
121 Out[11]: <...b instance at ...>
122
122
123 In [12]: ss
123 In [12]: ss
124 Out[12]: <...s instance at ...>
124 Out[12]: <...s instance at ...>
125
125
126 In [13]:
126 In [13]:
127
127
128 In [14]: %hist -op
128 In [14]: %hist -op
129 >>> class b:
129 >>> class b:
130 ... pass
130 ... pass
131 ...
131 ...
132 >>> class s(b):
132 >>> class s(b):
133 ... def __str__(self):
133 ... def __str__(self):
134 ... return 's'
134 ... return 's'
135 ...
135 ...
136 >>>
136 >>>
137 >>> class r(b):
137 >>> class r(b):
138 ... def __repr__(self):
138 ... def __repr__(self):
139 ... return 'r'
139 ... return 'r'
140 ...
140 ...
141 >>> class sr(s,r): pass
141 >>> class sr(s,r): pass
142 >>>
142 >>>
143 >>> bb=b()
143 >>> bb=b()
144 >>> ss=s()
144 >>> ss=s()
145 >>> rr=r()
145 >>> rr=r()
146 >>> ssrr=sr()
146 >>> ssrr=sr()
147 >>> bb
147 >>> bb
148 <...b instance at ...>
148 <...b instance at ...>
149 >>> ss
149 >>> ss
150 <...s instance at ...>
150 <...s instance at ...>
151 >>>
151 >>>
152 """
152 """
153
153
154 def test_shist():
154 def test_shist():
155 # Simple tests of ShadowHist class - test generator.
155 # Simple tests of ShadowHist class - test generator.
156 import os, shutil, tempfile
156 import os, shutil, tempfile
157
157
158 from IPython.utils import pickleshare
158 from IPython.utils import pickleshare
159 from IPython.core.history import ShadowHist
159 from IPython.core.history import ShadowHist
160
160
161 tfile = tempfile.mktemp('','tmp-ipython-')
161 tfile = tempfile.mktemp('','tmp-ipython-')
162
162
163 db = pickleshare.PickleShareDB(tfile)
163 db = pickleshare.PickleShareDB(tfile)
164 s = ShadowHist(db)
164 s = ShadowHist(db)
165 s.add('hello')
165 s.add('hello')
166 s.add('world')
166 s.add('world')
167 s.add('hello')
167 s.add('hello')
168 s.add('hello')
168 s.add('hello')
169 s.add('karhu')
169 s.add('karhu')
170
170
171 yield nt.assert_equals,s.all(),[(1, 'hello'), (2, 'world'), (3, 'karhu')]
171 yield nt.assert_equals,s.all(),[(1, 'hello'), (2, 'world'), (3, 'karhu')]
172
172
173 yield nt.assert_equal,s.get(2),'world'
173 yield nt.assert_equal,s.get(2),'world'
174
174
175 shutil.rmtree(tfile)
175 shutil.rmtree(tfile)
176
176
177
177
178 # XXX failing for now, until we get clearcmd out of quarantine. But we should
178 # XXX failing for now, until we get clearcmd out of quarantine. But we should
179 # fix this and revert the skip to happen only if numpy is not around.
179 # fix this and revert the skip to happen only if numpy is not around.
180 #@dec.skipif_not_numpy
180 #@dec.skipif_not_numpy
181 @dec.skipknownfailure
181 @dec.skipknownfailure
182 def test_numpy_clear_array_undec():
182 def test_numpy_clear_array_undec():
183 from IPython.extensions import clearcmd
183 from IPython.extensions import clearcmd
184
184
185 _ip.ex('import numpy as np')
185 _ip.ex('import numpy as np')
186 _ip.ex('a = np.empty(2)')
186 _ip.ex('a = np.empty(2)')
187 yield (nt.assert_true, 'a' in _ip.user_ns)
187 yield (nt.assert_true, 'a' in _ip.user_ns)
188 _ip.magic('clear array')
188 _ip.magic('clear array')
189 yield (nt.assert_false, 'a' in _ip.user_ns)
189 yield (nt.assert_false, 'a' in _ip.user_ns)
190
190
191
191
192 # Multiple tests for clipboard pasting
192 # Multiple tests for clipboard pasting
193 @dec.parametric
193 @dec.parametric
194 def test_paste():
194 def test_paste():
195 _ip = get_ipython()
195 _ip = get_ipython()
196 def paste(txt, flags='-q'):
196 def paste(txt, flags='-q'):
197 """Paste input text, by default in quiet mode"""
197 """Paste input text, by default in quiet mode"""
198 hooks.clipboard_get = lambda : txt
198 hooks.clipboard_get = lambda : txt
199 _ip.magic('paste '+flags)
199 _ip.magic('paste '+flags)
200
200
201 # Inject fake clipboard hook but save original so we can restore it later
201 # Inject fake clipboard hook but save original so we can restore it later
202 hooks = _ip.hooks
202 hooks = _ip.hooks
203 user_ns = _ip.user_ns
203 user_ns = _ip.user_ns
204 original_clip = hooks.clipboard_get
204 original_clip = hooks.clipboard_get
205
205
206 try:
206 try:
207 # This try/except with an emtpy except clause is here only because
207 # This try/except with an emtpy except clause is here only because
208 # try/yield/finally is invalid syntax in Python 2.4. This will be
208 # try/yield/finally is invalid syntax in Python 2.4. This will be
209 # removed when we drop 2.4-compatibility, and the emtpy except below
209 # removed when we drop 2.4-compatibility, and the emtpy except below
210 # will be changed to a finally.
210 # will be changed to a finally.
211
211
212 # Run tests with fake clipboard function
212 # Run tests with fake clipboard function
213 user_ns.pop('x', None)
213 user_ns.pop('x', None)
214 paste('x=1')
214 paste('x=1')
215 yield nt.assert_equal(user_ns['x'], 1)
215 yield nt.assert_equal(user_ns['x'], 1)
216
216
217 user_ns.pop('x', None)
217 user_ns.pop('x', None)
218 paste('>>> x=2')
218 paste('>>> x=2')
219 yield nt.assert_equal(user_ns['x'], 2)
219 yield nt.assert_equal(user_ns['x'], 2)
220
220
221 paste("""
221 paste("""
222 >>> x = [1,2,3]
222 >>> x = [1,2,3]
223 >>> y = []
223 >>> y = []
224 >>> for i in x:
224 >>> for i in x:
225 ... y.append(i**2)
225 ... y.append(i**2)
226 ...
226 ...
227 """)
227 """)
228 yield nt.assert_equal(user_ns['x'], [1,2,3])
228 yield nt.assert_equal(user_ns['x'], [1,2,3])
229 yield nt.assert_equal(user_ns['y'], [1,4,9])
229 yield nt.assert_equal(user_ns['y'], [1,4,9])
230
230
231 # Now, test that paste -r works
231 # Now, test that paste -r works
232 user_ns.pop('x', None)
232 user_ns.pop('x', None)
233 yield nt.assert_false('x' in user_ns)
233 yield nt.assert_false('x' in user_ns)
234 _ip.magic('paste -r')
234 _ip.magic('paste -r')
235 yield nt.assert_equal(user_ns['x'], [1,2,3])
235 yield nt.assert_equal(user_ns['x'], [1,2,3])
236
236
237 # Also test paste echoing, by temporarily faking the writer
237 # Also test paste echoing, by temporarily faking the writer
238 w = StringIO()
238 w = StringIO()
239 writer = _ip.write
239 writer = _ip.write
240 _ip.write = w.write
240 _ip.write = w.write
241 code = """
241 code = """
242 a = 100
242 a = 100
243 b = 200"""
243 b = 200"""
244 try:
244 try:
245 paste(code,'')
245 paste(code,'')
246 out = w.getvalue()
246 out = w.getvalue()
247 finally:
247 finally:
248 _ip.write = writer
248 _ip.write = writer
249 yield nt.assert_equal(user_ns['a'], 100)
249 yield nt.assert_equal(user_ns['a'], 100)
250 yield nt.assert_equal(user_ns['b'], 200)
250 yield nt.assert_equal(user_ns['b'], 200)
251 yield nt.assert_equal(out, code+"\n## -- End pasted text --\n")
251 yield nt.assert_equal(out, code+"\n## -- End pasted text --\n")
252
252
253 finally:
253 finally:
254 # This should be in a finally clause, instead of the bare except above.
254 # This should be in a finally clause, instead of the bare except above.
255 # Restore original hook
255 # Restore original hook
256 hooks.clipboard_get = original_clip
256 hooks.clipboard_get = original_clip
257
257
258
258
259 def test_time():
259 def test_time():
260 _ip.magic('time None')
260 _ip.magic('time None')
261
261
262
262
263 def doctest_time():
263 def doctest_time():
264 """
264 """
265 In [10]: %time None
265 In [10]: %time None
266 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
266 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
267 Wall time: 0.00 s
267 Wall time: 0.00 s
268 """
268 """
269
269
270
270 def test_doctest_mode():
271 def test_doctest_mode():
271 "Toggle doctest_mode twice, it should be a no-op and run without error"
272 "Toggle doctest_mode twice, it should be a no-op and run without error"
272 _ip.magic('doctest_mode')
273 _ip.magic('doctest_mode')
273 _ip.magic('doctest_mode')
274 _ip.magic('doctest_mode')
275
276
277 def test_parse_options():
278 """Tests for basic options parsing in magics."""
279 # These are only the most minimal of tests, more should be added later. At
280 # the very least we check that basic text/unicode calls work OK.
281 nt.assert_equal(_ip.parse_options('foo', '')[1], 'foo')
282 nt.assert_equal(_ip.parse_options(u'foo', '')[1], u'foo')
283
284
285 def test_dirops():
286 """Test various directory handling operations."""
287 curpath = lambda :os.path.splitdrive(os.getcwd())[1].replace('\\','/')
288
289 startdir = os.getcwd()
290 ipdir = _ip.ipython_dir
291 try:
292 _ip.magic('cd "%s"' % ipdir)
293 nt.assert_equal(curpath(), ipdir)
294 _ip.magic('cd -')
295 nt.assert_equal(curpath(), startdir)
296 _ip.magic('pushd "%s"' % ipdir)
297 nt.assert_equal(curpath(), ipdir)
298 _ip.magic('popd')
299 nt.assert_equal(curpath(), startdir)
300 finally:
301 os.chdir(startdir)
302
303
304 def check_cpaste(code, should_fail=False):
305 """Execute code via 'cpaste' and ensure it was executed, unless
306 should_fail is set.
307 """
308 _ip.user_ns['code_ran'] = False
309
310 src = StringIO()
311 src.write('\n')
312 src.write(code)
313 src.write('\n--\n')
314 src.seek(0)
315
316 stdin_save = sys.stdin
317 sys.stdin = src
274
318
319 try:
320 _ip.magic('cpaste')
321 except:
322 if not should_fail:
323 raise AssertionError("Failure not expected : '%s'" %
324 code)
325 else:
326 assert _ip.user_ns['code_ran']
327 if should_fail:
328 raise AssertionError("Failure expected : '%s'" % code)
329 finally:
330 sys.stdin = stdin_save
331
332
333 def test_cpaste():
334 """Test cpaste magic"""
335
336 def run():
337 """Marker function: sets a flag when executed.
338 """
339 _ip.user_ns['code_ran'] = True
340 return 'run' # return string so '+ run()' doesn't result in success
341
342 tests = {'pass': ["> > > run()",
343 ">>> > run()",
344 "+++ run()",
345 "++ run()",
346 " >>> run()"],
347
348 'fail': ["+ + run()",
349 " ++ run()"]}
350
351 _ip.user_ns['run'] = run
352
353 for code in tests['pass']:
354 check_cpaste(code)
355
356 for code in tests['fail']:
357 check_cpaste(code, should_fail=True)
@@ -1,59 +1,68 b''
1 """Tests for input manipulation machinery."""
1 """Tests for input manipulation machinery."""
2
2
3 #-----------------------------------------------------------------------------
3 #-----------------------------------------------------------------------------
4 # Imports
4 # Imports
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6 import nose.tools as nt
6 import nose.tools as nt
7
7
8 from IPython.testing import tools as tt, decorators as dec
8 from IPython.testing import tools as tt, decorators as dec
9 from IPython.testing.globalipapp import get_ipython
9 from IPython.testing.globalipapp import get_ipython
10
10
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12 # Tests
12 # Tests
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 ip = get_ipython()
14 ip = get_ipython()
15
15
16 @dec.parametric
16 @dec.parametric
17 def test_prefilter():
17 def test_prefilter():
18 """Test user input conversions"""
18 """Test user input conversions"""
19
19
20 # pairs of (raw, expected correct) input
20 # pairs of (raw, expected correct) input
21 pairs = [ ('2+2','2+2'),
21 pairs = [ ('2+2','2+2'),
22 ('>>> 2+2','2+2'),
22 ('>>> 2+2','2+2'),
23 ('>>> # This is a comment\n'
23 ('>>> # This is a comment\n'
24 '... 2+2',
24 '... 2+2',
25 '# This is a comment\n'
25 '# This is a comment\n'
26 '2+2'),
26 '2+2'),
27 # Some IPython input
27 # Some IPython input
28 ('In [1]: 1', '1'),
28 ('In [1]: 1', '1'),
29 ('In [2]: for i in range(5):\n'
29 ('In [2]: for i in range(5):\n'
30 ' ...: print i,',
30 ' ...: print i,',
31 'for i in range(5):\n'
31 'for i in range(5):\n'
32 ' print i,'),
32 ' print i,'),
33 ]
33 ]
34
34
35 for raw, correct in pairs:
35 for raw, correct in pairs:
36 yield nt.assert_equals(ip.prefilter(raw), correct)
36 yield nt.assert_equals(ip.prefilter(raw), correct)
37
37
38 @dec.parametric
38 @dec.parametric
39 def test_autocall_binops():
39 def test_autocall_binops():
40 """See https://bugs.launchpad.net/ipython/+bug/315706"""
40 """See https://bugs.launchpad.net/ipython/+bug/315706"""
41 ip.magic('autocall 2')
41 ip.magic('autocall 2')
42 f = lambda x: x
42 f = lambda x: x
43 ip.user_ns['f'] = f
43 ip.user_ns['f'] = f
44 try:
44 try:
45 yield nt.assert_equals(ip.prefilter('f 1'),'f(1)')
45 yield nt.assert_equals(ip.prefilter('f 1'),'f(1)')
46 for t in ['f +1', 'f -1']:
46 for t in ['f +1', 'f -1']:
47 yield nt.assert_equals(ip.prefilter(t), t)
47 yield nt.assert_equals(ip.prefilter(t), t)
48 finally:
48 finally:
49 ip.magic('autocall 0')
49 ip.magic('autocall 0')
50 del ip.user_ns['f']
50 del ip.user_ns['f']
51
51
52 @dec.parametric
52 @dec.parametric
53 def test_issue114():
53 def test_issue114():
54 """Check that multiline string literals don't expand as magic
54 """Check that multiline string literals don't expand as magic
55 see http://github.com/ipython/ipython/issues/#issue/114"""
55 see http://github.com/ipython/ipython/issues/#issue/114"""
56
56 template = '"""\n%s\n"""'
57 template = '"""\n%s\n"""'
57 for mgk in ip.lsmagic():
58 # Store the current value of multi_line_specials and turn it off before
58 raw = template % mgk
59 # running test, since it could be true (case in which the test doesn't make
59 yield nt.assert_equals(ip.prefilter(raw), raw)
60 # sense, as multiline string literals *will* expand as magic in that case).
61 msp = ip.prefilter_manager.multi_line_specials
62 ip.prefilter_manager.multi_line_specials = False
63 try:
64 for mgk in ip.lsmagic():
65 raw = template % mgk
66 yield nt.assert_equals(ip.prefilter(raw), raw)
67 finally:
68 ip.prefilter_manager.multi_line_specials = msp
1 NO CONTENT: file renamed from IPython/frontend/cocoa/__init__.py to IPython/deathrow/gui/__init__.py
NO CONTENT: file renamed from IPython/frontend/cocoa/__init__.py to IPython/deathrow/gui/__init__.py
1 NO CONTENT: file renamed from IPython/frontend/cocoa/tests/__init__.py to IPython/deathrow/gui/wx/__init__.py
NO CONTENT: file renamed from IPython/frontend/cocoa/tests/__init__.py to IPython/deathrow/gui/wx/__init__.py
1 NO CONTENT: file renamed from IPython/gui/wx/ipshell_nonblocking.py to IPython/deathrow/gui/wx/ipshell_nonblocking.py
NO CONTENT: file renamed from IPython/gui/wx/ipshell_nonblocking.py to IPython/deathrow/gui/wx/ipshell_nonblocking.py
1 NO CONTENT: file renamed from IPython/gui/wx/ipython_history.py to IPython/deathrow/gui/wx/ipython_history.py
NO CONTENT: file renamed from IPython/gui/wx/ipython_history.py to IPython/deathrow/gui/wx/ipython_history.py
1 NO CONTENT: file renamed from IPython/gui/wx/ipython_view.py to IPython/deathrow/gui/wx/ipython_view.py
NO CONTENT: file renamed from IPython/gui/wx/ipython_view.py to IPython/deathrow/gui/wx/ipython_view.py
1 NO CONTENT: file renamed from IPython/gui/wx/thread_ex.py to IPython/deathrow/gui/wx/thread_ex.py
NO CONTENT: file renamed from IPython/gui/wx/thread_ex.py to IPython/deathrow/gui/wx/thread_ex.py
1 NO CONTENT: file renamed from IPython/gui/wx/wxIPython.py to IPython/deathrow/gui/wx/wxIPython.py
NO CONTENT: file renamed from IPython/gui/wx/wxIPython.py to IPython/deathrow/gui/wx/wxIPython.py
1 NO CONTENT: file renamed from IPython/frontend/asyncfrontendbase.py to IPython/deathrow/oldfrontend/asyncfrontendbase.py
NO CONTENT: file renamed from IPython/frontend/asyncfrontendbase.py to IPython/deathrow/oldfrontend/asyncfrontendbase.py
1 NO CONTENT: file renamed from IPython/frontend/tests/__init__.py to IPython/deathrow/oldfrontend/cocoa/__init__.py
NO CONTENT: file renamed from IPython/frontend/tests/__init__.py to IPython/deathrow/oldfrontend/cocoa/__init__.py
1 NO CONTENT: file renamed from IPython/frontend/cocoa/cocoa_frontend.py to IPython/deathrow/oldfrontend/cocoa/cocoa_frontend.py
NO CONTENT: file renamed from IPython/frontend/cocoa/cocoa_frontend.py to IPython/deathrow/oldfrontend/cocoa/cocoa_frontend.py
1 NO CONTENT: file renamed from IPython/frontend/cocoa/examples/IPython1Sandbox/English.lproj/InfoPlist.strings to IPython/deathrow/oldfrontend/cocoa/examples/IPython1Sandbox/English.lproj/InfoPlist.strings
NO CONTENT: file renamed from IPython/frontend/cocoa/examples/IPython1Sandbox/English.lproj/InfoPlist.strings to IPython/deathrow/oldfrontend/cocoa/examples/IPython1Sandbox/English.lproj/InfoPlist.strings
1 NO CONTENT: file renamed from IPython/frontend/cocoa/examples/IPython1Sandbox/English.lproj/MainMenu.xib to IPython/deathrow/oldfrontend/cocoa/examples/IPython1Sandbox/English.lproj/MainMenu.xib
NO CONTENT: file renamed from IPython/frontend/cocoa/examples/IPython1Sandbox/English.lproj/MainMenu.xib to IPython/deathrow/oldfrontend/cocoa/examples/IPython1Sandbox/English.lproj/MainMenu.xib
1 NO CONTENT: file renamed from IPython/frontend/cocoa/examples/IPython1Sandbox/IPython1Sandbox.xcodeproj/project.pbxproj to IPython/deathrow/oldfrontend/cocoa/examples/IPython1Sandbox/IPython1Sandbox.xcodeproj/project.pbxproj
NO CONTENT: file renamed from IPython/frontend/cocoa/examples/IPython1Sandbox/IPython1Sandbox.xcodeproj/project.pbxproj to IPython/deathrow/oldfrontend/cocoa/examples/IPython1Sandbox/IPython1Sandbox.xcodeproj/project.pbxproj
1 NO CONTENT: file renamed from IPython/frontend/cocoa/examples/IPython1Sandbox/IPython1SandboxAppDelegate.py to IPython/deathrow/oldfrontend/cocoa/examples/IPython1Sandbox/IPython1SandboxAppDelegate.py
NO CONTENT: file renamed from IPython/frontend/cocoa/examples/IPython1Sandbox/IPython1SandboxAppDelegate.py to IPython/deathrow/oldfrontend/cocoa/examples/IPython1Sandbox/IPython1SandboxAppDelegate.py
1 NO CONTENT: file renamed from IPython/frontend/cocoa/examples/IPython1Sandbox/IPython1Sandbox_Prefix.pch to IPython/deathrow/oldfrontend/cocoa/examples/IPython1Sandbox/IPython1Sandbox_Prefix.pch
NO CONTENT: file renamed from IPython/frontend/cocoa/examples/IPython1Sandbox/IPython1Sandbox_Prefix.pch to IPython/deathrow/oldfrontend/cocoa/examples/IPython1Sandbox/IPython1Sandbox_Prefix.pch
1 NO CONTENT: file renamed from IPython/frontend/cocoa/examples/IPython1Sandbox/IPythonCocoaController Tests-Info.plist to IPython/deathrow/oldfrontend/cocoa/examples/IPython1Sandbox/IPythonCocoaController Tests-Info.plist
NO CONTENT: file renamed from IPython/frontend/cocoa/examples/IPython1Sandbox/IPythonCocoaController Tests-Info.plist to IPython/deathrow/oldfrontend/cocoa/examples/IPython1Sandbox/IPythonCocoaController Tests-Info.plist
1 NO CONTENT: file renamed from IPython/frontend/cocoa/examples/IPython1Sandbox/Info.plist to IPython/deathrow/oldfrontend/cocoa/examples/IPython1Sandbox/Info.plist
NO CONTENT: file renamed from IPython/frontend/cocoa/examples/IPython1Sandbox/Info.plist to IPython/deathrow/oldfrontend/cocoa/examples/IPython1Sandbox/Info.plist
1 NO CONTENT: file renamed from IPython/frontend/cocoa/examples/IPython1Sandbox/main.m to IPython/deathrow/oldfrontend/cocoa/examples/IPython1Sandbox/main.m
NO CONTENT: file renamed from IPython/frontend/cocoa/examples/IPython1Sandbox/main.m to IPython/deathrow/oldfrontend/cocoa/examples/IPython1Sandbox/main.m
1 NO CONTENT: file renamed from IPython/frontend/cocoa/examples/IPython1Sandbox/main.py to IPython/deathrow/oldfrontend/cocoa/examples/IPython1Sandbox/main.py
NO CONTENT: file renamed from IPython/frontend/cocoa/examples/IPython1Sandbox/main.py to IPython/deathrow/oldfrontend/cocoa/examples/IPython1Sandbox/main.py
1 NO CONTENT: file renamed from IPython/frontend/cocoa/plugin/CocoaFrontendPlugin.xcodeproj/project.pbxproj to IPython/deathrow/oldfrontend/cocoa/plugin/CocoaFrontendPlugin.xcodeproj/project.pbxproj
NO CONTENT: file renamed from IPython/frontend/cocoa/plugin/CocoaFrontendPlugin.xcodeproj/project.pbxproj to IPython/deathrow/oldfrontend/cocoa/plugin/CocoaFrontendPlugin.xcodeproj/project.pbxproj
1 NO CONTENT: file renamed from IPython/frontend/cocoa/plugin/IPythonCocoaFrontendLoader.py to IPython/deathrow/oldfrontend/cocoa/plugin/IPythonCocoaFrontendLoader.py
NO CONTENT: file renamed from IPython/frontend/cocoa/plugin/IPythonCocoaFrontendLoader.py to IPython/deathrow/oldfrontend/cocoa/plugin/IPythonCocoaFrontendLoader.py
1 NO CONTENT: file renamed from IPython/frontend/cocoa/plugin/Makefile to IPython/deathrow/oldfrontend/cocoa/plugin/Makefile
NO CONTENT: file renamed from IPython/frontend/cocoa/plugin/Makefile to IPython/deathrow/oldfrontend/cocoa/plugin/Makefile
1 NO CONTENT: file renamed from IPython/frontend/cocoa/plugin/Placeholder (Do Not Use)-Info.plist to IPython/deathrow/oldfrontend/cocoa/plugin/Placeholder (Do Not Use)-Info.plist
NO CONTENT: file renamed from IPython/frontend/cocoa/plugin/Placeholder (Do Not Use)-Info.plist to IPython/deathrow/oldfrontend/cocoa/plugin/Placeholder (Do Not Use)-Info.plist
1 NO CONTENT: file renamed from IPython/frontend/cocoa/plugin/plugins.mk to IPython/deathrow/oldfrontend/cocoa/plugin/plugins.mk
NO CONTENT: file renamed from IPython/frontend/cocoa/plugin/plugins.mk to IPython/deathrow/oldfrontend/cocoa/plugin/plugins.mk
1 NO CONTENT: file renamed from IPython/frontend/cocoa/plugin/setup.py to IPython/deathrow/oldfrontend/cocoa/plugin/setup.py
NO CONTENT: file renamed from IPython/frontend/cocoa/plugin/setup.py to IPython/deathrow/oldfrontend/cocoa/plugin/setup.py
1 NO CONTENT: file renamed from IPython/frontend/wx/__init__.py to IPython/deathrow/oldfrontend/cocoa/tests/__init__.py
NO CONTENT: file renamed from IPython/frontend/wx/__init__.py to IPython/deathrow/oldfrontend/cocoa/tests/__init__.py
1 NO CONTENT: file renamed from IPython/frontend/cocoa/tests/test_cocoa_frontend.py to IPython/deathrow/oldfrontend/cocoa/tests/test_cocoa_frontend.py
NO CONTENT: file renamed from IPython/frontend/cocoa/tests/test_cocoa_frontend.py to IPython/deathrow/oldfrontend/cocoa/tests/test_cocoa_frontend.py
1 NO CONTENT: file renamed from IPython/frontend/frontendbase.py to IPython/deathrow/oldfrontend/frontendbase.py
NO CONTENT: file renamed from IPython/frontend/frontendbase.py to IPython/deathrow/oldfrontend/frontendbase.py
1 NO CONTENT: file renamed from IPython/frontend/linefrontendbase.py to IPython/deathrow/oldfrontend/linefrontendbase.py
NO CONTENT: file renamed from IPython/frontend/linefrontendbase.py to IPython/deathrow/oldfrontend/linefrontendbase.py
1 NO CONTENT: file renamed from IPython/frontend/prefilterfrontend.py to IPython/deathrow/oldfrontend/prefilterfrontend.py
NO CONTENT: file renamed from IPython/frontend/prefilterfrontend.py to IPython/deathrow/oldfrontend/prefilterfrontend.py
1 NO CONTENT: file renamed from IPython/frontend/process/__init__.py to IPython/deathrow/oldfrontend/process/__init__.py
NO CONTENT: file renamed from IPython/frontend/process/__init__.py to IPython/deathrow/oldfrontend/process/__init__.py
1 NO CONTENT: file renamed from IPython/frontend/process/killableprocess.py to IPython/deathrow/oldfrontend/process/killableprocess.py
NO CONTENT: file renamed from IPython/frontend/process/killableprocess.py to IPython/deathrow/oldfrontend/process/killableprocess.py
1 NO CONTENT: file renamed from IPython/frontend/process/pipedprocess.py to IPython/deathrow/oldfrontend/process/pipedprocess.py
NO CONTENT: file renamed from IPython/frontend/process/pipedprocess.py to IPython/deathrow/oldfrontend/process/pipedprocess.py
1 NO CONTENT: file renamed from IPython/frontend/process/winprocess.py to IPython/deathrow/oldfrontend/process/winprocess.py
NO CONTENT: file renamed from IPython/frontend/process/winprocess.py to IPython/deathrow/oldfrontend/process/winprocess.py
1 NO CONTENT: file renamed from IPython/gui/__init__.py to IPython/deathrow/oldfrontend/tests/__init__.py
NO CONTENT: file renamed from IPython/gui/__init__.py to IPython/deathrow/oldfrontend/tests/__init__.py
1 NO CONTENT: file renamed from IPython/frontend/tests/test_asyncfrontendbase.py to IPython/deathrow/oldfrontend/tests/test_asyncfrontendbase.py
NO CONTENT: file renamed from IPython/frontend/tests/test_asyncfrontendbase.py to IPython/deathrow/oldfrontend/tests/test_asyncfrontendbase.py
1 NO CONTENT: file renamed from IPython/frontend/tests/test_frontendbase.py to IPython/deathrow/oldfrontend/tests/test_frontendbase.py
NO CONTENT: file renamed from IPython/frontend/tests/test_frontendbase.py to IPython/deathrow/oldfrontend/tests/test_frontendbase.py
1 NO CONTENT: file renamed from IPython/frontend/tests/test_linefrontend.py to IPython/deathrow/oldfrontend/tests/test_linefrontend.py
NO CONTENT: file renamed from IPython/frontend/tests/test_linefrontend.py to IPython/deathrow/oldfrontend/tests/test_linefrontend.py
1 NO CONTENT: file renamed from IPython/frontend/tests/test_prefilterfrontend.py to IPython/deathrow/oldfrontend/tests/test_prefilterfrontend.py
NO CONTENT: file renamed from IPython/frontend/tests/test_prefilterfrontend.py to IPython/deathrow/oldfrontend/tests/test_prefilterfrontend.py
1 NO CONTENT: file renamed from IPython/frontend/tests/test_process.py to IPython/deathrow/oldfrontend/tests/test_process.py
NO CONTENT: file renamed from IPython/frontend/tests/test_process.py to IPython/deathrow/oldfrontend/tests/test_process.py
1 NO CONTENT: file renamed from IPython/gui/wx/__init__.py to IPython/deathrow/oldfrontend/wx/__init__.py
NO CONTENT: file renamed from IPython/gui/wx/__init__.py to IPython/deathrow/oldfrontend/wx/__init__.py
1 NO CONTENT: file renamed from IPython/frontend/wx/console_widget.py to IPython/deathrow/oldfrontend/wx/console_widget.py
NO CONTENT: file renamed from IPython/frontend/wx/console_widget.py to IPython/deathrow/oldfrontend/wx/console_widget.py
1 NO CONTENT: file renamed from IPython/frontend/wx/ipythonx.py to IPython/deathrow/oldfrontend/wx/ipythonx.py
NO CONTENT: file renamed from IPython/frontend/wx/ipythonx.py to IPython/deathrow/oldfrontend/wx/ipythonx.py
1 NO CONTENT: file renamed from IPython/frontend/wx/wx_frontend.py to IPython/deathrow/oldfrontend/wx/wx_frontend.py
NO CONTENT: file renamed from IPython/frontend/wx/wx_frontend.py to IPython/deathrow/oldfrontend/wx/wx_frontend.py
1 NO CONTENT: file renamed from IPython/frontend/zopeinterface.py to IPython/deathrow/oldfrontend/zopeinterface.py
NO CONTENT: file renamed from IPython/frontend/zopeinterface.py to IPython/deathrow/oldfrontend/zopeinterface.py
1 NO CONTENT: file renamed from test/test_prefilter.py to IPython/deathrow/tests/test_prefilter.py
NO CONTENT: file renamed from test/test_prefilter.py to IPython/deathrow/tests/test_prefilter.py
@@ -1,441 +1,441 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 """Module for interactively running scripts.
2 """Module for interactively running scripts.
3
3
4 This module implements classes for interactively running scripts written for
4 This module implements classes for interactively running scripts written for
5 any system with a prompt which can be matched by a regexp suitable for
5 any system with a prompt which can be matched by a regexp suitable for
6 pexpect. It can be used to run as if they had been typed up interactively, an
6 pexpect. It can be used to run as if they had been typed up interactively, an
7 arbitrary series of commands for the target system.
7 arbitrary series of commands for the target system.
8
8
9 The module includes classes ready for IPython (with the default prompts),
9 The module includes classes ready for IPython (with the default prompts),
10 plain Python and SAGE, but making a new one is trivial. To see how to use it,
10 plain Python and SAGE, but making a new one is trivial. To see how to use it,
11 simply run the module as a script:
11 simply run the module as a script:
12
12
13 ./irunner.py --help
13 ./irunner.py --help
14
14
15
15
16 This is an extension of Ken Schutte <kschutte-AT-csail.mit.edu>'s script
16 This is an extension of Ken Schutte <kschutte-AT-csail.mit.edu>'s script
17 contributed on the ipython-user list:
17 contributed on the ipython-user list:
18
18
19 http://scipy.net/pipermail/ipython-user/2006-May/001705.html
19 http://scipy.net/pipermail/ipython-user/2006-May/001705.html
20
20
21
21
22 NOTES:
22 NOTES:
23
23
24 - This module requires pexpect, available in most linux distros, or which can
24 - This module requires pexpect, available in most linux distros, or which can
25 be downloaded from
25 be downloaded from
26
26
27 http://pexpect.sourceforge.net
27 http://pexpect.sourceforge.net
28
28
29 - Because pexpect only works under Unix or Windows-Cygwin, this has the same
29 - Because pexpect only works under Unix or Windows-Cygwin, this has the same
30 limitations. This means that it will NOT work under native windows Python.
30 limitations. This means that it will NOT work under native windows Python.
31 """
31 """
32
32
33 # Stdlib imports
33 # Stdlib imports
34 import optparse
34 import optparse
35 import os
35 import os
36 import sys
36 import sys
37
37
38 # Third-party modules.
38 # Third-party modules.
39 import pexpect
39 import pexpect
40
40
41 # Global usage strings, to avoid indentation issues when typing it below.
41 # Global usage strings, to avoid indentation issues when typing it below.
42 USAGE = """
42 USAGE = """
43 Interactive script runner, type: %s
43 Interactive script runner, type: %s
44
44
45 runner [opts] script_name
45 runner [opts] script_name
46 """
46 """
47
47
48 def pexpect_monkeypatch():
48 def pexpect_monkeypatch():
49 """Patch pexpect to prevent unhandled exceptions at VM teardown.
49 """Patch pexpect to prevent unhandled exceptions at VM teardown.
50
50
51 Calling this function will monkeypatch the pexpect.spawn class and modify
51 Calling this function will monkeypatch the pexpect.spawn class and modify
52 its __del__ method to make it more robust in the face of failures that can
52 its __del__ method to make it more robust in the face of failures that can
53 occur if it is called when the Python VM is shutting down.
53 occur if it is called when the Python VM is shutting down.
54
54
55 Since Python may fire __del__ methods arbitrarily late, it's possible for
55 Since Python may fire __del__ methods arbitrarily late, it's possible for
56 them to execute during the teardown of the Python VM itself. At this
56 them to execute during the teardown of the Python VM itself. At this
57 point, various builtin modules have been reset to None. Thus, the call to
57 point, various builtin modules have been reset to None. Thus, the call to
58 self.close() will trigger an exception because it tries to call os.close(),
58 self.close() will trigger an exception because it tries to call os.close(),
59 and os is now None.
59 and os is now None.
60 """
60 """
61
61
62 if pexpect.__version__[:3] >= '2.2':
62 if pexpect.__version__[:3] >= '2.2':
63 # No need to patch, fix is already the upstream version.
63 # No need to patch, fix is already the upstream version.
64 return
64 return
65
65
66 def __del__(self):
66 def __del__(self):
67 """This makes sure that no system resources are left open.
67 """This makes sure that no system resources are left open.
68 Python only garbage collects Python objects. OS file descriptors
68 Python only garbage collects Python objects. OS file descriptors
69 are not Python objects, so they must be handled explicitly.
69 are not Python objects, so they must be handled explicitly.
70 If the child file descriptor was opened outside of this class
70 If the child file descriptor was opened outside of this class
71 (passed to the constructor) then this does not close it.
71 (passed to the constructor) then this does not close it.
72 """
72 """
73 if not self.closed:
73 if not self.closed:
74 try:
74 try:
75 self.close()
75 self.close()
76 except AttributeError:
76 except AttributeError:
77 pass
77 pass
78
78
79 pexpect.spawn.__del__ = __del__
79 pexpect.spawn.__del__ = __del__
80
80
81 pexpect_monkeypatch()
81 pexpect_monkeypatch()
82
82
83 # The generic runner class
83 # The generic runner class
84 class InteractiveRunner(object):
84 class InteractiveRunner(object):
85 """Class to run a sequence of commands through an interactive program."""
85 """Class to run a sequence of commands through an interactive program."""
86
86
87 def __init__(self,program,prompts,args=None,out=sys.stdout,echo=True):
87 def __init__(self,program,prompts,args=None,out=sys.stdout,echo=True):
88 """Construct a runner.
88 """Construct a runner.
89
89
90 Inputs:
90 Inputs:
91
91
92 - program: command to execute the given program.
92 - program: command to execute the given program.
93
93
94 - prompts: a list of patterns to match as valid prompts, in the
94 - prompts: a list of patterns to match as valid prompts, in the
95 format used by pexpect. This basically means that it can be either
95 format used by pexpect. This basically means that it can be either
96 a string (to be compiled as a regular expression) or a list of such
96 a string (to be compiled as a regular expression) or a list of such
97 (it must be a true list, as pexpect does type checks).
97 (it must be a true list, as pexpect does type checks).
98
98
99 If more than one prompt is given, the first is treated as the main
99 If more than one prompt is given, the first is treated as the main
100 program prompt and the others as 'continuation' prompts, like
100 program prompt and the others as 'continuation' prompts, like
101 python's. This means that blank lines in the input source are
101 python's. This means that blank lines in the input source are
102 ommitted when the first prompt is matched, but are NOT ommitted when
102 ommitted when the first prompt is matched, but are NOT ommitted when
103 the continuation one matches, since this is how python signals the
103 the continuation one matches, since this is how python signals the
104 end of multiline input interactively.
104 end of multiline input interactively.
105
105
106 Optional inputs:
106 Optional inputs:
107
107
108 - args(None): optional list of strings to pass as arguments to the
108 - args(None): optional list of strings to pass as arguments to the
109 child program.
109 child program.
110
110
111 - out(sys.stdout): if given, an output stream to be used when writing
111 - out(sys.stdout): if given, an output stream to be used when writing
112 output. The only requirement is that it must have a .write() method.
112 output. The only requirement is that it must have a .write() method.
113
113
114 Public members not parameterized in the constructor:
114 Public members not parameterized in the constructor:
115
115
116 - delaybeforesend(0): Newer versions of pexpect have a delay before
116 - delaybeforesend(0): Newer versions of pexpect have a delay before
117 sending each new input. For our purposes here, it's typically best
117 sending each new input. For our purposes here, it's typically best
118 to just set this to zero, but if you encounter reliability problems
118 to just set this to zero, but if you encounter reliability problems
119 or want an interactive run to pause briefly at each prompt, just
119 or want an interactive run to pause briefly at each prompt, just
120 increase this value (it is measured in seconds). Note that this
120 increase this value (it is measured in seconds). Note that this
121 variable is not honored at all by older versions of pexpect.
121 variable is not honored at all by older versions of pexpect.
122 """
122 """
123
123
124 self.program = program
124 self.program = program
125 self.prompts = prompts
125 self.prompts = prompts
126 if args is None: args = []
126 if args is None: args = []
127 self.args = args
127 self.args = args
128 self.out = out
128 self.out = out
129 self.echo = echo
129 self.echo = echo
130 # Other public members which we don't make as parameters, but which
130 # Other public members which we don't make as parameters, but which
131 # users may occasionally want to tweak
131 # users may occasionally want to tweak
132 self.delaybeforesend = 0
132 self.delaybeforesend = 0
133
133
134 # Create child process and hold on to it so we don't have to re-create
134 # Create child process and hold on to it so we don't have to re-create
135 # for every single execution call
135 # for every single execution call
136 c = self.child = pexpect.spawn(self.program,self.args,timeout=None)
136 c = self.child = pexpect.spawn(self.program,self.args,timeout=None)
137 c.delaybeforesend = self.delaybeforesend
137 c.delaybeforesend = self.delaybeforesend
138 # pexpect hard-codes the terminal size as (24,80) (rows,columns).
138 # pexpect hard-codes the terminal size as (24,80) (rows,columns).
139 # This causes problems because any line longer than 80 characters gets
139 # This causes problems because any line longer than 80 characters gets
140 # completely overwrapped on the printed outptut (even though
140 # completely overwrapped on the printed outptut (even though
141 # internally the code runs fine). We reset this to 99 rows X 200
141 # internally the code runs fine). We reset this to 99 rows X 200
142 # columns (arbitrarily chosen), which should avoid problems in all
142 # columns (arbitrarily chosen), which should avoid problems in all
143 # reasonable cases.
143 # reasonable cases.
144 c.setwinsize(99,200)
144 c.setwinsize(99,200)
145
145
146 def close(self):
146 def close(self):
147 """close child process"""
147 """close child process"""
148
148
149 self.child.close()
149 self.child.close()
150
150
151 def run_file(self,fname,interact=False,get_output=False):
151 def run_file(self,fname,interact=False,get_output=False):
152 """Run the given file interactively.
152 """Run the given file interactively.
153
153
154 Inputs:
154 Inputs:
155
155
156 -fname: name of the file to execute.
156 -fname: name of the file to execute.
157
157
158 See the run_source docstring for the meaning of the optional
158 See the run_source docstring for the meaning of the optional
159 arguments."""
159 arguments."""
160
160
161 fobj = open(fname,'r')
161 fobj = open(fname,'r')
162 try:
162 try:
163 out = self.run_source(fobj,interact,get_output)
163 out = self.run_source(fobj,interact,get_output)
164 finally:
164 finally:
165 fobj.close()
165 fobj.close()
166 if get_output:
166 if get_output:
167 return out
167 return out
168
168
169 def run_source(self,source,interact=False,get_output=False):
169 def run_source(self,source,interact=False,get_output=False):
170 """Run the given source code interactively.
170 """Run the given source code interactively.
171
171
172 Inputs:
172 Inputs:
173
173
174 - source: a string of code to be executed, or an open file object we
174 - source: a string of code to be executed, or an open file object we
175 can iterate over.
175 can iterate over.
176
176
177 Optional inputs:
177 Optional inputs:
178
178
179 - interact(False): if true, start to interact with the running
179 - interact(False): if true, start to interact with the running
180 program at the end of the script. Otherwise, just exit.
180 program at the end of the script. Otherwise, just exit.
181
181
182 - get_output(False): if true, capture the output of the child process
182 - get_output(False): if true, capture the output of the child process
183 (filtering the input commands out) and return it as a string.
183 (filtering the input commands out) and return it as a string.
184
184
185 Returns:
185 Returns:
186 A string containing the process output, but only if requested.
186 A string containing the process output, but only if requested.
187 """
187 """
188
188
189 # if the source is a string, chop it up in lines so we can iterate
189 # if the source is a string, chop it up in lines so we can iterate
190 # over it just as if it were an open file.
190 # over it just as if it were an open file.
191 if not isinstance(source,file):
191 if not isinstance(source,file):
192 source = source.splitlines(True)
192 source = source.splitlines(True)
193
193
194 if self.echo:
194 if self.echo:
195 # normalize all strings we write to use the native OS line
195 # normalize all strings we write to use the native OS line
196 # separators.
196 # separators.
197 linesep = os.linesep
197 linesep = os.linesep
198 stdwrite = self.out.write
198 stdwrite = self.out.write
199 write = lambda s: stdwrite(s.replace('\r\n',linesep))
199 write = lambda s: stdwrite(s.replace('\r\n',linesep))
200 else:
200 else:
201 # Quiet mode, all writes are no-ops
201 # Quiet mode, all writes are no-ops
202 write = lambda s: None
202 write = lambda s: None
203
203
204 c = self.child
204 c = self.child
205 prompts = c.compile_pattern_list(self.prompts)
205 prompts = c.compile_pattern_list(self.prompts)
206 prompt_idx = c.expect_list(prompts)
206 prompt_idx = c.expect_list(prompts)
207
207
208 # Flag whether the script ends normally or not, to know whether we can
208 # Flag whether the script ends normally or not, to know whether we can
209 # do anything further with the underlying process.
209 # do anything further with the underlying process.
210 end_normal = True
210 end_normal = True
211
211
212 # If the output was requested, store it in a list for return at the end
212 # If the output was requested, store it in a list for return at the end
213 if get_output:
213 if get_output:
214 output = []
214 output = []
215 store_output = output.append
215 store_output = output.append
216
216
217 for cmd in source:
217 for cmd in source:
218 # skip blank lines for all matches to the 'main' prompt, while the
218 # skip blank lines for all matches to the 'main' prompt, while the
219 # secondary prompts do not
219 # secondary prompts do not
220 if prompt_idx==0 and \
220 if prompt_idx==0 and \
221 (cmd.isspace() or cmd.lstrip().startswith('#')):
221 (cmd.isspace() or cmd.lstrip().startswith('#')):
222 write(cmd)
222 write(cmd)
223 continue
223 continue
224
224
225 # write('AFTER: '+c.after) # dbg
225 # write('AFTER: '+c.after) # dbg
226 write(c.after)
226 write(c.after)
227 c.send(cmd)
227 c.send(cmd)
228 try:
228 try:
229 prompt_idx = c.expect_list(prompts)
229 prompt_idx = c.expect_list(prompts)
230 except pexpect.EOF:
230 except pexpect.EOF:
231 # this will happen if the child dies unexpectedly
231 # this will happen if the child dies unexpectedly
232 write(c.before)
232 write(c.before)
233 end_normal = False
233 end_normal = False
234 break
234 break
235
235
236 write(c.before)
236 write(c.before)
237
237
238 # With an echoing process, the output we get in c.before contains
238 # With an echoing process, the output we get in c.before contains
239 # the command sent, a newline, and then the actual process output
239 # the command sent, a newline, and then the actual process output
240 if get_output:
240 if get_output:
241 store_output(c.before[len(cmd+'\n'):])
241 store_output(c.before[len(cmd+'\n'):])
242 #write('CMD: <<%s>>' % cmd) # dbg
242 #write('CMD: <<%s>>' % cmd) # dbg
243 #write('OUTPUT: <<%s>>' % output[-1]) # dbg
243 #write('OUTPUT: <<%s>>' % output[-1]) # dbg
244
244
245 self.out.flush()
245 self.out.flush()
246 if end_normal:
246 if end_normal:
247 if interact:
247 if interact:
248 c.send('\n')
248 c.send('\n')
249 print '<< Starting interactive mode >>',
249 print '<< Starting interactive mode >>',
250 try:
250 try:
251 c.interact()
251 c.interact()
252 except OSError:
252 except OSError:
253 # This is what fires when the child stops. Simply print a
253 # This is what fires when the child stops. Simply print a
254 # newline so the system prompt is aligned. The extra
254 # newline so the system prompt is aligned. The extra
255 # space is there to make sure it gets printed, otherwise
255 # space is there to make sure it gets printed, otherwise
256 # OS buffering sometimes just suppresses it.
256 # OS buffering sometimes just suppresses it.
257 write(' \n')
257 write(' \n')
258 self.out.flush()
258 self.out.flush()
259 else:
259 else:
260 if interact:
260 if interact:
261 e="Further interaction is not possible: child process is dead."
261 e="Further interaction is not possible: child process is dead."
262 print >> sys.stderr, e
262 print >> sys.stderr, e
263
263
264 # Leave the child ready for more input later on, otherwise select just
264 # Leave the child ready for more input later on, otherwise select just
265 # hangs on the second invocation.
265 # hangs on the second invocation.
266 c.send('\n')
266 c.send('\n')
267
267
268 # Return any requested output
268 # Return any requested output
269 if get_output:
269 if get_output:
270 return ''.join(output)
270 return ''.join(output)
271
271
272 def main(self,argv=None):
272 def main(self,argv=None):
273 """Run as a command-line script."""
273 """Run as a command-line script."""
274
274
275 parser = optparse.OptionParser(usage=USAGE % self.__class__.__name__)
275 parser = optparse.OptionParser(usage=USAGE % self.__class__.__name__)
276 newopt = parser.add_option
276 newopt = parser.add_option
277 newopt('-i','--interact',action='store_true',default=False,
277 newopt('-i','--interact',action='store_true',default=False,
278 help='Interact with the program after the script is run.')
278 help='Interact with the program after the script is run.')
279
279
280 opts,args = parser.parse_args(argv)
280 opts,args = parser.parse_args(argv)
281
281
282 if len(args) != 1:
282 if len(args) != 1:
283 print >> sys.stderr,"You must supply exactly one file to run."
283 print >> sys.stderr,"You must supply exactly one file to run."
284 sys.exit(1)
284 sys.exit(1)
285
285
286 self.run_file(args[0],opts.interact)
286 self.run_file(args[0],opts.interact)
287
287
288
288
289 # Specific runners for particular programs
289 # Specific runners for particular programs
290 class IPythonRunner(InteractiveRunner):
290 class IPythonRunner(InteractiveRunner):
291 """Interactive IPython runner.
291 """Interactive IPython runner.
292
292
293 This initalizes IPython in 'nocolor' mode for simplicity. This lets us
293 This initalizes IPython in 'nocolor' mode for simplicity. This lets us
294 avoid having to write a regexp that matches ANSI sequences, though pexpect
294 avoid having to write a regexp that matches ANSI sequences, though pexpect
295 does support them. If anyone contributes patches for ANSI color support,
295 does support them. If anyone contributes patches for ANSI color support,
296 they will be welcome.
296 they will be welcome.
297
297
298 It also sets the prompts manually, since the prompt regexps for
298 It also sets the prompts manually, since the prompt regexps for
299 pexpect need to be matched to the actual prompts, so user-customized
299 pexpect need to be matched to the actual prompts, so user-customized
300 prompts would break this.
300 prompts would break this.
301 """
301 """
302
302
303 def __init__(self,program = 'ipython',args=None,out=sys.stdout,echo=True):
303 def __init__(self,program = 'ipython',args=None,out=sys.stdout,echo=True):
304 """New runner, optionally passing the ipython command to use."""
304 """New runner, optionally passing the ipython command to use."""
305
305
306 args0 = ['--colors','NoColor',
306 args0 = ['--colors','NoColor',
307 '-pi1','In [\\#]: ',
307 '-pi1','In [\\#]: ',
308 '-pi2',' .\\D.: ',
308 '-pi2',' .\\D.: ',
309 '--noterm-title',
309 '--no-term-title',
310 '--no-auto-indent']
310 '--no-autoindent']
311 if args is None: args = args0
311 if args is None: args = args0
312 else: args = args0 + args
312 else: args = args0 + args
313 prompts = [r'In \[\d+\]: ',r' \.*: ']
313 prompts = [r'In \[\d+\]: ',r' \.*: ']
314 InteractiveRunner.__init__(self,program,prompts,args,out,echo)
314 InteractiveRunner.__init__(self,program,prompts,args,out,echo)
315
315
316
316
317 class PythonRunner(InteractiveRunner):
317 class PythonRunner(InteractiveRunner):
318 """Interactive Python runner."""
318 """Interactive Python runner."""
319
319
320 def __init__(self,program='python',args=None,out=sys.stdout,echo=True):
320 def __init__(self,program='python',args=None,out=sys.stdout,echo=True):
321 """New runner, optionally passing the python command to use."""
321 """New runner, optionally passing the python command to use."""
322
322
323 prompts = [r'>>> ',r'\.\.\. ']
323 prompts = [r'>>> ',r'\.\.\. ']
324 InteractiveRunner.__init__(self,program,prompts,args,out,echo)
324 InteractiveRunner.__init__(self,program,prompts,args,out,echo)
325
325
326
326
327 class SAGERunner(InteractiveRunner):
327 class SAGERunner(InteractiveRunner):
328 """Interactive SAGE runner.
328 """Interactive SAGE runner.
329
329
330 WARNING: this runner only works if you manually configure your SAGE copy
330 WARNING: this runner only works if you manually configure your SAGE copy
331 to use 'colors NoColor' in the ipythonrc config file, since currently the
331 to use 'colors NoColor' in the ipythonrc config file, since currently the
332 prompt matching regexp does not identify color sequences."""
332 prompt matching regexp does not identify color sequences."""
333
333
334 def __init__(self,program='sage',args=None,out=sys.stdout,echo=True):
334 def __init__(self,program='sage',args=None,out=sys.stdout,echo=True):
335 """New runner, optionally passing the sage command to use."""
335 """New runner, optionally passing the sage command to use."""
336
336
337 prompts = ['sage: ',r'\s*\.\.\. ']
337 prompts = ['sage: ',r'\s*\.\.\. ']
338 InteractiveRunner.__init__(self,program,prompts,args,out,echo)
338 InteractiveRunner.__init__(self,program,prompts,args,out,echo)
339
339
340
340
341 class RunnerFactory(object):
341 class RunnerFactory(object):
342 """Code runner factory.
342 """Code runner factory.
343
343
344 This class provides an IPython code runner, but enforces that only one
344 This class provides an IPython code runner, but enforces that only one
345 runner is ever instantiated. The runner is created based on the extension
345 runner is ever instantiated. The runner is created based on the extension
346 of the first file to run, and it raises an exception if a runner is later
346 of the first file to run, and it raises an exception if a runner is later
347 requested for a different extension type.
347 requested for a different extension type.
348
348
349 This ensures that we don't generate example files for doctest with a mix of
349 This ensures that we don't generate example files for doctest with a mix of
350 python and ipython syntax.
350 python and ipython syntax.
351 """
351 """
352
352
353 def __init__(self,out=sys.stdout):
353 def __init__(self,out=sys.stdout):
354 """Instantiate a code runner."""
354 """Instantiate a code runner."""
355
355
356 self.out = out
356 self.out = out
357 self.runner = None
357 self.runner = None
358 self.runnerClass = None
358 self.runnerClass = None
359
359
360 def _makeRunner(self,runnerClass):
360 def _makeRunner(self,runnerClass):
361 self.runnerClass = runnerClass
361 self.runnerClass = runnerClass
362 self.runner = runnerClass(out=self.out)
362 self.runner = runnerClass(out=self.out)
363 return self.runner
363 return self.runner
364
364
365 def __call__(self,fname):
365 def __call__(self,fname):
366 """Return a runner for the given filename."""
366 """Return a runner for the given filename."""
367
367
368 if fname.endswith('.py'):
368 if fname.endswith('.py'):
369 runnerClass = PythonRunner
369 runnerClass = PythonRunner
370 elif fname.endswith('.ipy'):
370 elif fname.endswith('.ipy'):
371 runnerClass = IPythonRunner
371 runnerClass = IPythonRunner
372 else:
372 else:
373 raise ValueError('Unknown file type for Runner: %r' % fname)
373 raise ValueError('Unknown file type for Runner: %r' % fname)
374
374
375 if self.runner is None:
375 if self.runner is None:
376 return self._makeRunner(runnerClass)
376 return self._makeRunner(runnerClass)
377 else:
377 else:
378 if runnerClass==self.runnerClass:
378 if runnerClass==self.runnerClass:
379 return self.runner
379 return self.runner
380 else:
380 else:
381 e='A runner of type %r can not run file %r' % \
381 e='A runner of type %r can not run file %r' % \
382 (self.runnerClass,fname)
382 (self.runnerClass,fname)
383 raise ValueError(e)
383 raise ValueError(e)
384
384
385
385
386 # Global usage string, to avoid indentation issues if typed in a function def.
386 # Global usage string, to avoid indentation issues if typed in a function def.
387 MAIN_USAGE = """
387 MAIN_USAGE = """
388 %prog [options] file_to_run
388 %prog [options] file_to_run
389
389
390 This is an interface to the various interactive runners available in this
390 This is an interface to the various interactive runners available in this
391 module. If you want to pass specific options to one of the runners, you need
391 module. If you want to pass specific options to one of the runners, you need
392 to first terminate the main options with a '--', and then provide the runner's
392 to first terminate the main options with a '--', and then provide the runner's
393 options. For example:
393 options. For example:
394
394
395 irunner.py --python -- --help
395 irunner.py --python -- --help
396
396
397 will pass --help to the python runner. Similarly,
397 will pass --help to the python runner. Similarly,
398
398
399 irunner.py --ipython -- --interact script.ipy
399 irunner.py --ipython -- --interact script.ipy
400
400
401 will run the script.ipy file under the IPython runner, and then will start to
401 will run the script.ipy file under the IPython runner, and then will start to
402 interact with IPython at the end of the script (instead of exiting).
402 interact with IPython at the end of the script (instead of exiting).
403
403
404 The already implemented runners are listed below; adding one for a new program
404 The already implemented runners are listed below; adding one for a new program
405 is a trivial task, see the source for examples.
405 is a trivial task, see the source for examples.
406
406
407 WARNING: the SAGE runner only works if you manually configure your SAGE copy
407 WARNING: the SAGE runner only works if you manually configure your SAGE copy
408 to use 'colors NoColor' in the ipythonrc config file, since currently the
408 to use 'colors NoColor' in the ipythonrc config file, since currently the
409 prompt matching regexp does not identify color sequences.
409 prompt matching regexp does not identify color sequences.
410 """
410 """
411
411
412 def main():
412 def main():
413 """Run as a command-line script."""
413 """Run as a command-line script."""
414
414
415 parser = optparse.OptionParser(usage=MAIN_USAGE)
415 parser = optparse.OptionParser(usage=MAIN_USAGE)
416 newopt = parser.add_option
416 newopt = parser.add_option
417 parser.set_defaults(mode='ipython')
417 parser.set_defaults(mode='ipython')
418 newopt('--ipython',action='store_const',dest='mode',const='ipython',
418 newopt('--ipython',action='store_const',dest='mode',const='ipython',
419 help='IPython interactive runner (default).')
419 help='IPython interactive runner (default).')
420 newopt('--python',action='store_const',dest='mode',const='python',
420 newopt('--python',action='store_const',dest='mode',const='python',
421 help='Python interactive runner.')
421 help='Python interactive runner.')
422 newopt('--sage',action='store_const',dest='mode',const='sage',
422 newopt('--sage',action='store_const',dest='mode',const='sage',
423 help='SAGE interactive runner.')
423 help='SAGE interactive runner.')
424
424
425 opts,args = parser.parse_args()
425 opts,args = parser.parse_args()
426 runners = dict(ipython=IPythonRunner,
426 runners = dict(ipython=IPythonRunner,
427 python=PythonRunner,
427 python=PythonRunner,
428 sage=SAGERunner)
428 sage=SAGERunner)
429
429
430 try:
430 try:
431 ext = os.path.splitext(args[0])[-1]
431 ext = os.path.splitext(args[0])[-1]
432 except IndexError:
432 except IndexError:
433 ext = ''
433 ext = ''
434 modes = {'.ipy':'ipython',
434 modes = {'.ipy':'ipython',
435 '.py':'python',
435 '.py':'python',
436 '.sage':'sage'}
436 '.sage':'sage'}
437 mode = modes.get(ext,opts.mode)
437 mode = modes.get(ext,opts.mode)
438 runners[mode]().main(args)
438 runners[mode]().main(args)
439
439
440 if __name__ == '__main__':
440 if __name__ == '__main__':
441 main()
441 main()
@@ -1,168 +1,162 b''
1 #!/usr/bin/env python
2 """Test suite for the irunner module.
1 """Test suite for the irunner module.
3
2
4 Not the most elegant or fine-grained, but it does cover at least the bulk
3 Not the most elegant or fine-grained, but it does cover at least the bulk
5 functionality."""
4 functionality."""
6
5
7 # Global to make tests extra verbose and help debugging
6 # Global to make tests extra verbose and help debugging
8 VERBOSE = True
7 VERBOSE = True
9
8
10 # stdlib imports
9 # stdlib imports
11 import cStringIO as StringIO
10 import cStringIO as StringIO
12 import sys
11 import sys
13 import unittest
12 import unittest
14
13
15 # IPython imports
14 # IPython imports
16 from IPython import irunner
15 from IPython.lib import irunner
17
16
18 # Testing code begins
17 # Testing code begins
19 class RunnerTestCase(unittest.TestCase):
18 class RunnerTestCase(unittest.TestCase):
20
19
21 def setUp(self):
20 def setUp(self):
22 self.out = StringIO.StringIO()
21 self.out = StringIO.StringIO()
23 #self.out = sys.stdout
22 #self.out = sys.stdout
24
23
25 def _test_runner(self,runner,source,output):
24 def _test_runner(self,runner,source,output):
26 """Test that a given runner's input/output match."""
25 """Test that a given runner's input/output match."""
27
26
28 runner.run_source(source)
27 runner.run_source(source)
29 out = self.out.getvalue()
28 out = self.out.getvalue()
30 #out = ''
29 #out = ''
31 # this output contains nasty \r\n lineends, and the initial ipython
30 # this output contains nasty \r\n lineends, and the initial ipython
32 # banner. clean it up for comparison
31 # banner. clean it up for comparison, removing lines of whitespace
33 output_l = output.split()
32 output_l = [l for l in output.splitlines() if l and not l.isspace()]
34 out_l = out.split()
33 out_l = [l for l in out.splitlines() if l and not l.isspace()]
35 mismatch = 0
34 mismatch = 0
36 #if len(output_l) != len(out_l):
35 if len(output_l) != len(out_l):
37 # self.fail('mismatch in number of lines')
36 self.fail('mismatch in number of lines')
38 for n in range(len(output_l)):
37 for n in range(len(output_l)):
39 # Do a line-by-line comparison
38 # Do a line-by-line comparison
40 ol1 = output_l[n].strip()
39 ol1 = output_l[n].strip()
41 ol2 = out_l[n].strip()
40 ol2 = out_l[n].strip()
42 if ol1 != ol2:
41 if ol1 != ol2:
43 mismatch += 1
42 mismatch += 1
44 if VERBOSE:
43 if VERBOSE:
45 print '<<< line %s does not match:' % n
44 print '<<< line %s does not match:' % n
46 print repr(ol1)
45 print repr(ol1)
47 print repr(ol2)
46 print repr(ol2)
48 print '>>>'
47 print '>>>'
49 self.assert_(mismatch==0,'Number of mismatched lines: %s' %
48 self.assert_(mismatch==0,'Number of mismatched lines: %s' %
50 mismatch)
49 mismatch)
51
50
52 def testIPython(self):
51 def testIPython(self):
53 """Test the IPython runner."""
52 """Test the IPython runner."""
54 source = """
53 source = """
55 print 'hello, this is python'
54 print 'hello, this is python'
56
57 # some more code
55 # some more code
58 x=1;y=2
56 x=1;y=2
59 x+y**2
57 x+y**2
60
58
61 # An example of autocall functionality
59 # An example of autocall functionality
62 from math import *
60 from math import *
63 autocall 1
61 autocall 1
64 cos pi
62 cos pi
65 autocall 0
63 autocall 0
66 cos pi
64 cos pi
67 cos(pi)
65 cos(pi)
68
66
69 for i in range(5):
67 for i in range(5):
70 print i,
68 print i,
71
69
72 print "that's all folks!"
70 print "that's all folks!"
73
71
74 %Exit
72 %Exit
75 """
73 """
76 output = """\
74 output = """\
77 In [1]: print 'hello, this is python'
75 In [1]: print 'hello, this is python'
78 hello, this is python
76 hello, this is python
79
77
80
78
81 # some more code
79 # some more code
82 In [2]: x=1;y=2
80 In [2]: x=1;y=2
83
81
84 In [3]: x+y**2
82 In [3]: x+y**2
85 Out[3]: 5
83 Out[3]: 5
86
84
87
85
88 # An example of autocall functionality
86 # An example of autocall functionality
89 In [4]: from math import *
87 In [4]: from math import *
90
88
91 In [5]: autocall 1
89 In [5]: autocall 1
92 Automatic calling is: Smart
90 Automatic calling is: Smart
93
91
94 In [6]: cos pi
92 In [6]: cos pi
95 ------> cos(pi)
93 ------> cos(pi)
96 Out[6]: -1.0
94 Out[6]: -1.0
97
95
98 In [7]: autocall 0
96 In [7]: autocall 0
99 Automatic calling is: OFF
97 Automatic calling is: OFF
100
98
101 In [8]: cos pi
99 In [8]: cos pi
102 ------------------------------------------------------------
103 File "<ipython console>", line 1
100 File "<ipython console>", line 1
104 cos pi
101 cos pi
105 ^
102 ^
106 <type 'exceptions.SyntaxError'>: invalid syntax
103 SyntaxError: invalid syntax
107
104
108
105
109 In [9]: cos(pi)
106 In [9]: cos(pi)
110 Out[9]: -1.0
107 Out[9]: -1.0
111
108
112
109
113 In [10]: for i in range(5):
110 In [10]: for i in range(5):
114 ....: print i,
111 ....: print i,
115 ....:
112 ....:
116 0 1 2 3 4
113 0 1 2 3 4
117
114
118 In [11]: print "that's all folks!"
115 In [11]: print "that's all folks!"
119 that's all folks!
116 that's all folks!
120
117
121
118
122 In [12]: %Exit
119 In [12]: %Exit
123 """
120 """
124 runner = irunner.IPythonRunner(out=self.out)
121 runner = irunner.IPythonRunner(out=self.out)
125 self._test_runner(runner,source,output)
122 self._test_runner(runner,source,output)
126
123
127 def testPython(self):
124 def testPython(self):
128 """Test the Python runner."""
125 """Test the Python runner."""
129 runner = irunner.PythonRunner(out=self.out)
126 runner = irunner.PythonRunner(out=self.out)
130 source = """
127 source = """
131 print 'hello, this is python'
128 print 'hello, this is python'
132
129
133 # some more code
130 # some more code
134 x=1;y=2
131 x=1;y=2
135 x+y**2
132 x+y**2
136
133
137 from math import *
134 from math import *
138 cos(pi)
135 cos(pi)
139
136
140 for i in range(5):
137 for i in range(5):
141 print i,
138 print i,
142
139
143 print "that's all folks!"
140 print "that's all folks!"
144 """
141 """
145 output = """\
142 output = """\
146 >>> print 'hello, this is python'
143 >>> print 'hello, this is python'
147 hello, this is python
144 hello, this is python
148
145
149 # some more code
146 # some more code
150 >>> x=1;y=2
147 >>> x=1;y=2
151 >>> x+y**2
148 >>> x+y**2
152 5
149 5
153
150
154 >>> from math import *
151 >>> from math import *
155 >>> cos(pi)
152 >>> cos(pi)
156 -1.0
153 -1.0
157
154
158 >>> for i in range(5):
155 >>> for i in range(5):
159 ... print i,
156 ... print i,
160 ...
157 ...
161 0 1 2 3 4
158 0 1 2 3 4
162 >>> print "that's all folks!"
159 >>> print "that's all folks!"
163 that's all folks!
160 that's all folks!
164 """
161 """
165 self._test_runner(runner,source,output)
162 self._test_runner(runner,source,output)
166
167 if __name__ == '__main__':
168 unittest.main()
@@ -1,467 +1,446 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """IPython Test Suite Runner.
2 """IPython Test Suite Runner.
3
3
4 This module provides a main entry point to a user script to test IPython
4 This module provides a main entry point to a user script to test IPython
5 itself from the command line. There are two ways of running this script:
5 itself from the command line. There are two ways of running this script:
6
6
7 1. With the syntax `iptest all`. This runs our entire test suite by
7 1. With the syntax `iptest all`. This runs our entire test suite by
8 calling this script (with different arguments) or trial recursively. This
8 calling this script (with different arguments) or trial recursively. This
9 causes modules and package to be tested in different processes, using nose
9 causes modules and package to be tested in different processes, using nose
10 or trial where appropriate.
10 or trial where appropriate.
11 2. With the regular nose syntax, like `iptest -vvs IPython`. In this form
11 2. With the regular nose syntax, like `iptest -vvs IPython`. In this form
12 the script simply calls nose, but with special command line flags and
12 the script simply calls nose, but with special command line flags and
13 plugins loaded.
13 plugins loaded.
14
14
15 For now, this script requires that both nose and twisted are installed. This
15 For now, this script requires that both nose and twisted are installed. This
16 will change in the future.
16 will change in the future.
17 """
17 """
18
18
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20 # Copyright (C) 2009 The IPython Development Team
20 # Copyright (C) 2009 The IPython Development Team
21 #
21 #
22 # Distributed under the terms of the BSD License. The full license is in
22 # Distributed under the terms of the BSD License. The full license is in
23 # the file COPYING, distributed as part of this software.
23 # the file COPYING, distributed as part of this software.
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25
25
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27 # Imports
27 # Imports
28 #-----------------------------------------------------------------------------
28 #-----------------------------------------------------------------------------
29
29
30 # Stdlib
30 # Stdlib
31 import os
31 import os
32 import os.path as path
32 import os.path as path
33 import signal
33 import signal
34 import sys
34 import sys
35 import subprocess
35 import subprocess
36 import tempfile
36 import tempfile
37 import time
37 import time
38 import warnings
38 import warnings
39
39
40 # Note: monkeypatch!
40 # Note: monkeypatch!
41 # We need to monkeypatch a small problem in nose itself first, before importing
41 # We need to monkeypatch a small problem in nose itself first, before importing
42 # it for actual use. This should get into nose upstream, but its release cycle
42 # it for actual use. This should get into nose upstream, but its release cycle
43 # is slow and we need it for our parametric tests to work correctly.
43 # is slow and we need it for our parametric tests to work correctly.
44 from IPython.testing import nosepatch
44 from IPython.testing import nosepatch
45 # Now, proceed to import nose itself
45 # Now, proceed to import nose itself
46 import nose.plugins.builtin
46 import nose.plugins.builtin
47 from nose.core import TestProgram
47 from nose.core import TestProgram
48
48
49 # Our own imports
49 # Our own imports
50 from IPython.utils.path import get_ipython_module_path
50 from IPython.utils.path import get_ipython_module_path
51 from IPython.utils.process import find_cmd, pycmd2argv
51 from IPython.utils.process import find_cmd, pycmd2argv
52 from IPython.utils.sysinfo import sys_info
52 from IPython.utils.sysinfo import sys_info
53
53
54 from IPython.testing import globalipapp
54 from IPython.testing import globalipapp
55 from IPython.testing.plugin.ipdoctest import IPythonDoctest
55 from IPython.testing.plugin.ipdoctest import IPythonDoctest
56
56
57 pjoin = path.join
57 pjoin = path.join
58
58
59
59
60 #-----------------------------------------------------------------------------
60 #-----------------------------------------------------------------------------
61 # Globals
61 # Globals
62 #-----------------------------------------------------------------------------
62 #-----------------------------------------------------------------------------
63
63
64
64
65 #-----------------------------------------------------------------------------
65 #-----------------------------------------------------------------------------
66 # Warnings control
66 # Warnings control
67 #-----------------------------------------------------------------------------
67 #-----------------------------------------------------------------------------
68
68
69 # Twisted generates annoying warnings with Python 2.6, as will do other code
69 # Twisted generates annoying warnings with Python 2.6, as will do other code
70 # that imports 'sets' as of today
70 # that imports 'sets' as of today
71 warnings.filterwarnings('ignore', 'the sets module is deprecated',
71 warnings.filterwarnings('ignore', 'the sets module is deprecated',
72 DeprecationWarning )
72 DeprecationWarning )
73
73
74 # This one also comes from Twisted
74 # This one also comes from Twisted
75 warnings.filterwarnings('ignore', 'the sha module is deprecated',
75 warnings.filterwarnings('ignore', 'the sha module is deprecated',
76 DeprecationWarning)
76 DeprecationWarning)
77
77
78 # Wx on Fedora11 spits these out
78 # Wx on Fedora11 spits these out
79 warnings.filterwarnings('ignore', 'wxPython/wxWidgets release number mismatch',
79 warnings.filterwarnings('ignore', 'wxPython/wxWidgets release number mismatch',
80 UserWarning)
80 UserWarning)
81
81
82 #-----------------------------------------------------------------------------
82 #-----------------------------------------------------------------------------
83 # Logic for skipping doctests
83 # Logic for skipping doctests
84 #-----------------------------------------------------------------------------
84 #-----------------------------------------------------------------------------
85
85
86 def test_for(mod):
86 def test_for(mod):
87 """Test to see if mod is importable."""
87 """Test to see if mod is importable."""
88 try:
88 try:
89 __import__(mod)
89 __import__(mod)
90 except (ImportError, RuntimeError):
90 except (ImportError, RuntimeError):
91 # GTK reports Runtime error if it can't be initialized even if it's
91 # GTK reports Runtime error if it can't be initialized even if it's
92 # importable.
92 # importable.
93 return False
93 return False
94 else:
94 else:
95 return True
95 return True
96
96
97 # Global dict where we can store information on what we have and what we don't
97 # Global dict where we can store information on what we have and what we don't
98 # have available at test run time
98 # have available at test run time
99 have = {}
99 have = {}
100
100
101 have['curses'] = test_for('_curses')
101 have['curses'] = test_for('_curses')
102 have['wx'] = test_for('wx')
102 have['wx'] = test_for('wx')
103 have['wx.aui'] = test_for('wx.aui')
103 have['wx.aui'] = test_for('wx.aui')
104 have['zope.interface'] = test_for('zope.interface')
104 have['zope.interface'] = test_for('zope.interface')
105 have['twisted'] = test_for('twisted')
105 have['twisted'] = test_for('twisted')
106 have['foolscap'] = test_for('foolscap')
106 have['foolscap'] = test_for('foolscap')
107 have['objc'] = test_for('objc')
108 have['pexpect'] = test_for('pexpect')
107 have['pexpect'] = test_for('pexpect')
109 have['gtk'] = test_for('gtk')
108 have['gtk'] = test_for('gtk')
110 have['gobject'] = test_for('gobject')
109 have['gobject'] = test_for('gobject')
111
110
112 #-----------------------------------------------------------------------------
111 #-----------------------------------------------------------------------------
113 # Functions and classes
112 # Functions and classes
114 #-----------------------------------------------------------------------------
113 #-----------------------------------------------------------------------------
115
114
116 def report():
115 def report():
117 """Return a string with a summary report of test-related variables."""
116 """Return a string with a summary report of test-related variables."""
118
117
119 out = [ sys_info() ]
118 out = [ sys_info() ]
120
119
121 avail = []
120 avail = []
122 not_avail = []
121 not_avail = []
123
122
124 for k, is_avail in have.items():
123 for k, is_avail in have.items():
125 if is_avail:
124 if is_avail:
126 avail.append(k)
125 avail.append(k)
127 else:
126 else:
128 not_avail.append(k)
127 not_avail.append(k)
129
128
130 if avail:
129 if avail:
131 out.append('\nTools and libraries available at test time:\n')
130 out.append('\nTools and libraries available at test time:\n')
132 avail.sort()
131 avail.sort()
133 out.append(' ' + ' '.join(avail)+'\n')
132 out.append(' ' + ' '.join(avail)+'\n')
134
133
135 if not_avail:
134 if not_avail:
136 out.append('\nTools and libraries NOT available at test time:\n')
135 out.append('\nTools and libraries NOT available at test time:\n')
137 not_avail.sort()
136 not_avail.sort()
138 out.append(' ' + ' '.join(not_avail)+'\n')
137 out.append(' ' + ' '.join(not_avail)+'\n')
139
138
140 return ''.join(out)
139 return ''.join(out)
141
140
142
141
143 def make_exclude():
142 def make_exclude():
144 """Make patterns of modules and packages to exclude from testing.
143 """Make patterns of modules and packages to exclude from testing.
145
144
146 For the IPythonDoctest plugin, we need to exclude certain patterns that
145 For the IPythonDoctest plugin, we need to exclude certain patterns that
147 cause testing problems. We should strive to minimize the number of
146 cause testing problems. We should strive to minimize the number of
148 skipped modules, since this means untested code.
147 skipped modules, since this means untested code.
149
148
150 These modules and packages will NOT get scanned by nose at all for tests.
149 These modules and packages will NOT get scanned by nose at all for tests.
151 """
150 """
152 # Simple utility to make IPython paths more readably, we need a lot of
151 # Simple utility to make IPython paths more readably, we need a lot of
153 # these below
152 # these below
154 ipjoin = lambda *paths: pjoin('IPython', *paths)
153 ipjoin = lambda *paths: pjoin('IPython', *paths)
155
154
156 exclusions = [ipjoin('external'),
155 exclusions = [ipjoin('external'),
157 ipjoin('frontend', 'process', 'winprocess.py'),
158 # Deprecated old Shell and iplib modules, skip to avoid
156 # Deprecated old Shell and iplib modules, skip to avoid
159 # warnings
157 # warnings
160 ipjoin('Shell'),
158 ipjoin('Shell'),
161 ipjoin('iplib'),
159 ipjoin('iplib'),
162 pjoin('IPython_doctest_plugin'),
160 pjoin('IPython_doctest_plugin'),
163 ipjoin('quarantine'),
161 ipjoin('quarantine'),
164 ipjoin('deathrow'),
162 ipjoin('deathrow'),
165 ipjoin('testing', 'attic'),
163 ipjoin('testing', 'attic'),
166 # This guy is probably attic material
164 # This guy is probably attic material
167 ipjoin('testing', 'mkdoctests'),
165 ipjoin('testing', 'mkdoctests'),
168 # Testing inputhook will need a lot of thought, to figure out
166 # Testing inputhook will need a lot of thought, to figure out
169 # how to have tests that don't lock up with the gui event
167 # how to have tests that don't lock up with the gui event
170 # loops in the picture
168 # loops in the picture
171 ipjoin('lib', 'inputhook'),
169 ipjoin('lib', 'inputhook'),
172 # Config files aren't really importable stand-alone
170 # Config files aren't really importable stand-alone
173 ipjoin('config', 'default'),
171 ipjoin('config', 'default'),
174 ipjoin('config', 'profile'),
172 ipjoin('config', 'profile'),
175 ]
173 ]
176
174
177 if not have['wx']:
175 if not have['wx']:
178 exclusions.append(ipjoin('gui'))
179 exclusions.append(ipjoin('frontend', 'wx'))
180 exclusions.append(ipjoin('lib', 'inputhookwx'))
176 exclusions.append(ipjoin('lib', 'inputhookwx'))
181
177
182 if not have['gtk'] or not have['gobject']:
178 if not have['gtk'] or not have['gobject']:
183 exclusions.append(ipjoin('lib', 'inputhookgtk'))
179 exclusions.append(ipjoin('lib', 'inputhookgtk'))
184
180
185 if not have['wx.aui']:
186 exclusions.append(ipjoin('gui', 'wx', 'wxIPython'))
187
188 if not have['objc']:
189 exclusions.append(ipjoin('frontend', 'cocoa'))
190
191 # These have to be skipped on win32 because the use echo, rm, cd, etc.
181 # These have to be skipped on win32 because the use echo, rm, cd, etc.
192 # See ticket https://bugs.launchpad.net/bugs/366982
182 # See ticket https://bugs.launchpad.net/bugs/366982
193 if sys.platform == 'win32':
183 if sys.platform == 'win32':
194 exclusions.append(ipjoin('testing', 'plugin', 'test_exampleip'))
184 exclusions.append(ipjoin('testing', 'plugin', 'test_exampleip'))
195 exclusions.append(ipjoin('testing', 'plugin', 'dtexample'))
185 exclusions.append(ipjoin('testing', 'plugin', 'dtexample'))
196
186
197 if not have['pexpect']:
187 if not have['pexpect']:
198 exclusions.extend([ipjoin('scripts', 'irunner'),
188 exclusions.extend([ipjoin('scripts', 'irunner'),
199 ipjoin('lib', 'irunner')])
189 ipjoin('lib', 'irunner')])
200
190
201 # This is scary. We still have things in frontend and testing that
191 # This is scary. We still have things in frontend and testing that
202 # are being tested by nose that use twisted. We need to rethink
192 # are being tested by nose that use twisted. We need to rethink
203 # how we are isolating dependencies in testing.
193 # how we are isolating dependencies in testing.
204 if not (have['twisted'] and have['zope.interface'] and have['foolscap']):
194 if not (have['twisted'] and have['zope.interface'] and have['foolscap']):
205 exclusions.extend(
195 exclusions.extend(
206 [ipjoin('frontend', 'asyncfrontendbase'),
196 [ipjoin('testing', 'parametric'),
207 ipjoin('frontend', 'prefilterfrontend'),
208 ipjoin('frontend', 'frontendbase'),
209 ipjoin('frontend', 'linefrontendbase'),
210 ipjoin('frontend', 'tests', 'test_linefrontend'),
211 ipjoin('frontend', 'tests', 'test_frontendbase'),
212 ipjoin('frontend', 'tests', 'test_prefilterfrontend'),
213 ipjoin('frontend', 'tests', 'test_asyncfrontendbase'),
214 ipjoin('testing', 'parametric'),
215 ipjoin('testing', 'util'),
197 ipjoin('testing', 'util'),
216 ipjoin('testing', 'tests', 'test_decorators_trial'),
198 ipjoin('testing', 'tests', 'test_decorators_trial'),
217 ] )
199 ] )
218
200
219 # This is needed for the reg-exp to match on win32 in the ipdoctest plugin.
201 # This is needed for the reg-exp to match on win32 in the ipdoctest plugin.
220 if sys.platform == 'win32':
202 if sys.platform == 'win32':
221 exclusions = [s.replace('\\','\\\\') for s in exclusions]
203 exclusions = [s.replace('\\','\\\\') for s in exclusions]
222
204
223 return exclusions
205 return exclusions
224
206
225
207
226 class IPTester(object):
208 class IPTester(object):
227 """Call that calls iptest or trial in a subprocess.
209 """Call that calls iptest or trial in a subprocess.
228 """
210 """
229 #: string, name of test runner that will be called
211 #: string, name of test runner that will be called
230 runner = None
212 runner = None
231 #: list, parameters for test runner
213 #: list, parameters for test runner
232 params = None
214 params = None
233 #: list, arguments of system call to be made to call test runner
215 #: list, arguments of system call to be made to call test runner
234 call_args = None
216 call_args = None
235 #: list, process ids of subprocesses we start (for cleanup)
217 #: list, process ids of subprocesses we start (for cleanup)
236 pids = None
218 pids = None
237
219
238 def __init__(self, runner='iptest', params=None):
220 def __init__(self, runner='iptest', params=None):
239 """Create new test runner."""
221 """Create new test runner."""
240 p = os.path
222 p = os.path
241 if runner == 'iptest':
223 if runner == 'iptest':
242 iptest_app = get_ipython_module_path('IPython.testing.iptest')
224 iptest_app = get_ipython_module_path('IPython.testing.iptest')
243 self.runner = pycmd2argv(iptest_app) + sys.argv[1:]
225 self.runner = pycmd2argv(iptest_app) + sys.argv[1:]
244 elif runner == 'trial':
226 elif runner == 'trial':
245 # For trial, it needs to be installed system-wide
227 # For trial, it needs to be installed system-wide
246 self.runner = pycmd2argv(p.abspath(find_cmd('trial')))
228 self.runner = pycmd2argv(p.abspath(find_cmd('trial')))
247 else:
229 else:
248 raise Exception('Not a valid test runner: %s' % repr(runner))
230 raise Exception('Not a valid test runner: %s' % repr(runner))
249 if params is None:
231 if params is None:
250 params = []
232 params = []
251 if isinstance(params, str):
233 if isinstance(params, str):
252 params = [params]
234 params = [params]
253 self.params = params
235 self.params = params
254
236
255 # Assemble call
237 # Assemble call
256 self.call_args = self.runner+self.params
238 self.call_args = self.runner+self.params
257
239
258 # Store pids of anything we start to clean up on deletion, if possible
240 # Store pids of anything we start to clean up on deletion, if possible
259 # (on posix only, since win32 has no os.kill)
241 # (on posix only, since win32 has no os.kill)
260 self.pids = []
242 self.pids = []
261
243
262 if sys.platform == 'win32':
244 if sys.platform == 'win32':
263 def _run_cmd(self):
245 def _run_cmd(self):
264 # On Windows, use os.system instead of subprocess.call, because I
246 # On Windows, use os.system instead of subprocess.call, because I
265 # was having problems with subprocess and I just don't know enough
247 # was having problems with subprocess and I just don't know enough
266 # about win32 to debug this reliably. Os.system may be the 'old
248 # about win32 to debug this reliably. Os.system may be the 'old
267 # fashioned' way to do it, but it works just fine. If someone
249 # fashioned' way to do it, but it works just fine. If someone
268 # later can clean this up that's fine, as long as the tests run
250 # later can clean this up that's fine, as long as the tests run
269 # reliably in win32.
251 # reliably in win32.
270 # What types of problems are you having. They may be related to
252 # What types of problems are you having. They may be related to
271 # running Python in unboffered mode. BG.
253 # running Python in unboffered mode. BG.
272 return os.system(' '.join(self.call_args))
254 return os.system(' '.join(self.call_args))
273 else:
255 else:
274 def _run_cmd(self):
256 def _run_cmd(self):
275 #print >> sys.stderr, '*** CMD:', ' '.join(self.call_args) # dbg
257 #print >> sys.stderr, '*** CMD:', ' '.join(self.call_args) # dbg
276 subp = subprocess.Popen(self.call_args)
258 subp = subprocess.Popen(self.call_args)
277 self.pids.append(subp.pid)
259 self.pids.append(subp.pid)
278 # If this fails, the pid will be left in self.pids and cleaned up
260 # If this fails, the pid will be left in self.pids and cleaned up
279 # later, but if the wait call succeeds, then we can clear the
261 # later, but if the wait call succeeds, then we can clear the
280 # stored pid.
262 # stored pid.
281 retcode = subp.wait()
263 retcode = subp.wait()
282 self.pids.pop()
264 self.pids.pop()
283 return retcode
265 return retcode
284
266
285 def run(self):
267 def run(self):
286 """Run the stored commands"""
268 """Run the stored commands"""
287 try:
269 try:
288 return self._run_cmd()
270 return self._run_cmd()
289 except:
271 except:
290 import traceback
272 import traceback
291 traceback.print_exc()
273 traceback.print_exc()
292 return 1 # signal failure
274 return 1 # signal failure
293
275
294 def __del__(self):
276 def __del__(self):
295 """Cleanup on exit by killing any leftover processes."""
277 """Cleanup on exit by killing any leftover processes."""
296
278
297 if not hasattr(os, 'kill'):
279 if not hasattr(os, 'kill'):
298 return
280 return
299
281
300 for pid in self.pids:
282 for pid in self.pids:
301 try:
283 try:
302 print 'Cleaning stale PID:', pid
284 print 'Cleaning stale PID:', pid
303 os.kill(pid, signal.SIGKILL)
285 os.kill(pid, signal.SIGKILL)
304 except OSError:
286 except OSError:
305 # This is just a best effort, if we fail or the process was
287 # This is just a best effort, if we fail or the process was
306 # really gone, ignore it.
288 # really gone, ignore it.
307 pass
289 pass
308
290
309
291
310 def make_runners():
292 def make_runners():
311 """Define the top-level packages that need to be tested.
293 """Define the top-level packages that need to be tested.
312 """
294 """
313
295
314 # Packages to be tested via nose, that only depend on the stdlib
296 # Packages to be tested via nose, that only depend on the stdlib
315 nose_pkg_names = ['config', 'core', 'extensions', 'frontend', 'lib',
297 nose_pkg_names = ['config', 'core', 'extensions', 'frontend', 'lib',
316 'scripts', 'testing', 'utils' ]
298 'scripts', 'testing', 'utils' ]
317 # The machinery in kernel needs twisted for real testing
299 # The machinery in kernel needs twisted for real testing
318 trial_pkg_names = []
300 trial_pkg_names = []
319
301
320 if have['wx']:
321 nose_pkg_names.append('gui')
322
323 # And add twisted ones if conditions are met
302 # And add twisted ones if conditions are met
324 if have['zope.interface'] and have['twisted'] and have['foolscap']:
303 if have['zope.interface'] and have['twisted'] and have['foolscap']:
325 # We only list IPython.kernel for testing using twisted.trial as
304 # We only list IPython.kernel for testing using twisted.trial as
326 # nose and twisted.trial have conflicts that make the testing system
305 # nose and twisted.trial have conflicts that make the testing system
327 # unstable.
306 # unstable.
328 trial_pkg_names.append('kernel')
307 trial_pkg_names.append('kernel')
329
308
330 # For debugging this code, only load quick stuff
309 # For debugging this code, only load quick stuff
331 #nose_pkg_names = ['core', 'extensions'] # dbg
310 #nose_pkg_names = ['core', 'extensions'] # dbg
332 #trial_pkg_names = [] # dbg
311 #trial_pkg_names = [] # dbg
333
312
334 # Make fully qualified package names prepending 'IPython.' to our name lists
313 # Make fully qualified package names prepending 'IPython.' to our name lists
335 nose_packages = ['IPython.%s' % m for m in nose_pkg_names ]
314 nose_packages = ['IPython.%s' % m for m in nose_pkg_names ]
336 trial_packages = ['IPython.%s' % m for m in trial_pkg_names ]
315 trial_packages = ['IPython.%s' % m for m in trial_pkg_names ]
337
316
338 # Make runners
317 # Make runners
339 runners = [ (v, IPTester('iptest', params=v)) for v in nose_packages ]
318 runners = [ (v, IPTester('iptest', params=v)) for v in nose_packages ]
340 runners.extend([ (v, IPTester('trial', params=v)) for v in trial_packages ])
319 runners.extend([ (v, IPTester('trial', params=v)) for v in trial_packages ])
341
320
342 return runners
321 return runners
343
322
344
323
345 def run_iptest():
324 def run_iptest():
346 """Run the IPython test suite using nose.
325 """Run the IPython test suite using nose.
347
326
348 This function is called when this script is **not** called with the form
327 This function is called when this script is **not** called with the form
349 `iptest all`. It simply calls nose with appropriate command line flags
328 `iptest all`. It simply calls nose with appropriate command line flags
350 and accepts all of the standard nose arguments.
329 and accepts all of the standard nose arguments.
351 """
330 """
352
331
353 warnings.filterwarnings('ignore',
332 warnings.filterwarnings('ignore',
354 'This will be removed soon. Use IPython.testing.util instead')
333 'This will be removed soon. Use IPython.testing.util instead')
355
334
356 argv = sys.argv + [ '--detailed-errors', # extra info in tracebacks
335 argv = sys.argv + [ '--detailed-errors', # extra info in tracebacks
357
336
358 # Loading ipdoctest causes problems with Twisted, but
337 # Loading ipdoctest causes problems with Twisted, but
359 # our test suite runner now separates things and runs
338 # our test suite runner now separates things and runs
360 # all Twisted tests with trial.
339 # all Twisted tests with trial.
361 '--with-ipdoctest',
340 '--with-ipdoctest',
362 '--ipdoctest-tests','--ipdoctest-extension=txt',
341 '--ipdoctest-tests','--ipdoctest-extension=txt',
363
342
364 # We add --exe because of setuptools' imbecility (it
343 # We add --exe because of setuptools' imbecility (it
365 # blindly does chmod +x on ALL files). Nose does the
344 # blindly does chmod +x on ALL files). Nose does the
366 # right thing and it tries to avoid executables,
345 # right thing and it tries to avoid executables,
367 # setuptools unfortunately forces our hand here. This
346 # setuptools unfortunately forces our hand here. This
368 # has been discussed on the distutils list and the
347 # has been discussed on the distutils list and the
369 # setuptools devs refuse to fix this problem!
348 # setuptools devs refuse to fix this problem!
370 '--exe',
349 '--exe',
371 ]
350 ]
372
351
373 if nose.__version__ >= '0.11':
352 if nose.__version__ >= '0.11':
374 # I don't fully understand why we need this one, but depending on what
353 # I don't fully understand why we need this one, but depending on what
375 # directory the test suite is run from, if we don't give it, 0 tests
354 # directory the test suite is run from, if we don't give it, 0 tests
376 # get run. Specifically, if the test suite is run from the source dir
355 # get run. Specifically, if the test suite is run from the source dir
377 # with an argument (like 'iptest.py IPython.core', 0 tests are run,
356 # with an argument (like 'iptest.py IPython.core', 0 tests are run,
378 # even if the same call done in this directory works fine). It appears
357 # even if the same call done in this directory works fine). It appears
379 # that if the requested package is in the current dir, nose bails early
358 # that if the requested package is in the current dir, nose bails early
380 # by default. Since it's otherwise harmless, leave it in by default
359 # by default. Since it's otherwise harmless, leave it in by default
381 # for nose >= 0.11, though unfortunately nose 0.10 doesn't support it.
360 # for nose >= 0.11, though unfortunately nose 0.10 doesn't support it.
382 argv.append('--traverse-namespace')
361 argv.append('--traverse-namespace')
383
362
384 # Construct list of plugins, omitting the existing doctest plugin, which
363 # Construct list of plugins, omitting the existing doctest plugin, which
385 # ours replaces (and extends).
364 # ours replaces (and extends).
386 plugins = [IPythonDoctest(make_exclude())]
365 plugins = [IPythonDoctest(make_exclude())]
387 for p in nose.plugins.builtin.plugins:
366 for p in nose.plugins.builtin.plugins:
388 plug = p()
367 plug = p()
389 if plug.name == 'doctest':
368 if plug.name == 'doctest':
390 continue
369 continue
391 plugins.append(plug)
370 plugins.append(plug)
392
371
393 # We need a global ipython running in this process
372 # We need a global ipython running in this process
394 globalipapp.start_ipython()
373 globalipapp.start_ipython()
395 # Now nose can run
374 # Now nose can run
396 TestProgram(argv=argv, plugins=plugins)
375 TestProgram(argv=argv, plugins=plugins)
397
376
398
377
399 def run_iptestall():
378 def run_iptestall():
400 """Run the entire IPython test suite by calling nose and trial.
379 """Run the entire IPython test suite by calling nose and trial.
401
380
402 This function constructs :class:`IPTester` instances for all IPython
381 This function constructs :class:`IPTester` instances for all IPython
403 modules and package and then runs each of them. This causes the modules
382 modules and package and then runs each of them. This causes the modules
404 and packages of IPython to be tested each in their own subprocess using
383 and packages of IPython to be tested each in their own subprocess using
405 nose or twisted.trial appropriately.
384 nose or twisted.trial appropriately.
406 """
385 """
407
386
408 runners = make_runners()
387 runners = make_runners()
409
388
410 # Run the test runners in a temporary dir so we can nuke it when finished
389 # Run the test runners in a temporary dir so we can nuke it when finished
411 # to clean up any junk files left over by accident. This also makes it
390 # to clean up any junk files left over by accident. This also makes it
412 # robust against being run in non-writeable directories by mistake, as the
391 # robust against being run in non-writeable directories by mistake, as the
413 # temp dir will always be user-writeable.
392 # temp dir will always be user-writeable.
414 curdir = os.getcwd()
393 curdir = os.getcwd()
415 testdir = tempfile.gettempdir()
394 testdir = tempfile.gettempdir()
416 os.chdir(testdir)
395 os.chdir(testdir)
417
396
418 # Run all test runners, tracking execution time
397 # Run all test runners, tracking execution time
419 failed = []
398 failed = []
420 t_start = time.time()
399 t_start = time.time()
421 try:
400 try:
422 for (name, runner) in runners:
401 for (name, runner) in runners:
423 print '*'*70
402 print '*'*70
424 print 'IPython test group:',name
403 print 'IPython test group:',name
425 res = runner.run()
404 res = runner.run()
426 if res:
405 if res:
427 failed.append( (name, runner) )
406 failed.append( (name, runner) )
428 finally:
407 finally:
429 os.chdir(curdir)
408 os.chdir(curdir)
430 t_end = time.time()
409 t_end = time.time()
431 t_tests = t_end - t_start
410 t_tests = t_end - t_start
432 nrunners = len(runners)
411 nrunners = len(runners)
433 nfail = len(failed)
412 nfail = len(failed)
434 # summarize results
413 # summarize results
435 print
414 print
436 print '*'*70
415 print '*'*70
437 print 'Test suite completed for system with the following information:'
416 print 'Test suite completed for system with the following information:'
438 print report()
417 print report()
439 print 'Ran %s test groups in %.3fs' % (nrunners, t_tests)
418 print 'Ran %s test groups in %.3fs' % (nrunners, t_tests)
440 print
419 print
441 print 'Status:'
420 print 'Status:'
442 if not failed:
421 if not failed:
443 print 'OK'
422 print 'OK'
444 else:
423 else:
445 # If anything went wrong, point out what command to rerun manually to
424 # If anything went wrong, point out what command to rerun manually to
446 # see the actual errors and individual summary
425 # see the actual errors and individual summary
447 print 'ERROR - %s out of %s test groups failed.' % (nfail, nrunners)
426 print 'ERROR - %s out of %s test groups failed.' % (nfail, nrunners)
448 for name, failed_runner in failed:
427 for name, failed_runner in failed:
449 print '-'*40
428 print '-'*40
450 print 'Runner failed:',name
429 print 'Runner failed:',name
451 print 'You may wish to rerun this one individually, with:'
430 print 'You may wish to rerun this one individually, with:'
452 print ' '.join(failed_runner.call_args)
431 print ' '.join(failed_runner.call_args)
453 print
432 print
454
433
455
434
456 def main():
435 def main():
457 for arg in sys.argv[1:]:
436 for arg in sys.argv[1:]:
458 if arg.startswith('IPython'):
437 if arg.startswith('IPython'):
459 # This is in-process
438 # This is in-process
460 run_iptest()
439 run_iptest()
461 else:
440 else:
462 # This starts subprocesses
441 # This starts subprocesses
463 run_iptestall()
442 run_iptestall()
464
443
465
444
466 if __name__ == '__main__':
445 if __name__ == '__main__':
467 main()
446 main()
@@ -1,368 +1,367 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """
2 """
3 Utilities for working with external processes.
3 Utilities for working with external processes.
4 """
4 """
5
5
6 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
7 # Copyright (C) 2008-2009 The IPython Development Team
7 # Copyright (C) 2008-2009 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 import os
17 import os
18 import sys
18 import sys
19 import shlex
19 import shlex
20 import subprocess
20 import subprocess
21
21
22 from IPython.utils.terminal import set_term_title
22 from IPython.utils.terminal import set_term_title
23
23
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25 # Code
25 # Code
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27
27
28
28
29 class FindCmdError(Exception):
29 class FindCmdError(Exception):
30 pass
30 pass
31
31
32
32
33 def _find_cmd(cmd):
33 def _find_cmd(cmd):
34 """Find the full path to a command using which."""
34 """Find the full path to a command using which."""
35 return os.popen('which %s' % cmd).read().strip()
35 return os.popen('which %s' % cmd).read().strip()
36
36
37
37
38 if os.name == 'posix':
38 if os.name == 'posix':
39 def _find_cmd(cmd):
39 def _find_cmd(cmd):
40 """Find the full path to a command using which."""
40 """Find the full path to a command using which."""
41 return getoutputerror('/usr/bin/env which %s' % cmd)[0]
41 return getoutputerror('/usr/bin/env which %s' % cmd)[0]
42
42
43
43
44 if sys.platform == 'win32':
44 if sys.platform == 'win32':
45 def _find_cmd(cmd):
45 def _find_cmd(cmd):
46 """Find the full path to a .bat or .exe using the win32api module."""
46 """Find the full path to a .bat or .exe using the win32api module."""
47 try:
47 try:
48 from win32api import SearchPath
48 from win32api import SearchPath
49 except ImportError:
49 except ImportError:
50 raise ImportError('you need to have pywin32 installed for this to work')
50 raise ImportError('you need to have pywin32 installed for this to work')
51 else:
51 else:
52 PATH = os.environ['PATH']
52 PATH = os.environ['PATH']
53 extensions = ['.exe', '.com', '.bat', '.py']
53 extensions = ['.exe', '.com', '.bat', '.py']
54 path = None
54 path = None
55 for ext in extensions:
55 for ext in extensions:
56 try:
56 try:
57 path = SearchPath(PATH,cmd + ext)[0]
57 path = SearchPath(PATH,cmd + ext)[0]
58 except:
58 except:
59 pass
59 pass
60 if path is None:
60 if path is None:
61 raise OSError("command %r not found" % cmd)
61 raise OSError("command %r not found" % cmd)
62 else:
62 else:
63 return path
63 return path
64
64
65
65
66 def find_cmd(cmd):
66 def find_cmd(cmd):
67 """Find absolute path to executable cmd in a cross platform manner.
67 """Find absolute path to executable cmd in a cross platform manner.
68
68
69 This function tries to determine the full path to a command line program
69 This function tries to determine the full path to a command line program
70 using `which` on Unix/Linux/OS X and `win32api` on Windows. Most of the
70 using `which` on Unix/Linux/OS X and `win32api` on Windows. Most of the
71 time it will use the version that is first on the users `PATH`. If
71 time it will use the version that is first on the users `PATH`. If
72 cmd is `python` return `sys.executable`.
72 cmd is `python` return `sys.executable`.
73
73
74 Warning, don't use this to find IPython command line programs as there
74 Warning, don't use this to find IPython command line programs as there
75 is a risk you will find the wrong one. Instead find those using the
75 is a risk you will find the wrong one. Instead find those using the
76 following code and looking for the application itself::
76 following code and looking for the application itself::
77
77
78 from IPython.utils.path import get_ipython_module_path
78 from IPython.utils.path import get_ipython_module_path
79 from IPython.utils.process import pycmd2argv
79 from IPython.utils.process import pycmd2argv
80 argv = pycmd2argv(get_ipython_module_path('IPython.core.ipapp'))
80 argv = pycmd2argv(get_ipython_module_path('IPython.core.ipapp'))
81
81
82 Parameters
82 Parameters
83 ----------
83 ----------
84 cmd : str
84 cmd : str
85 The command line program to look for.
85 The command line program to look for.
86 """
86 """
87 if cmd == 'python':
87 if cmd == 'python':
88 return os.path.abspath(sys.executable)
88 return os.path.abspath(sys.executable)
89 try:
89 try:
90 path = _find_cmd(cmd)
90 path = _find_cmd(cmd)
91 except OSError:
91 except OSError:
92 raise FindCmdError('command could not be found: %s' % cmd)
92 raise FindCmdError('command could not be found: %s' % cmd)
93 # which returns empty if not found
93 # which returns empty if not found
94 if path == '':
94 if path == '':
95 raise FindCmdError('command could not be found: %s' % cmd)
95 raise FindCmdError('command could not be found: %s' % cmd)
96 return os.path.abspath(path)
96 return os.path.abspath(path)
97
97
98
98
99 def pycmd2argv(cmd):
99 def pycmd2argv(cmd):
100 r"""Take the path of a python command and return a list (argv-style).
100 r"""Take the path of a python command and return a list (argv-style).
101
101
102 This only works on Python based command line programs and will find the
102 This only works on Python based command line programs and will find the
103 location of the ``python`` executable using ``sys.executable`` to make
103 location of the ``python`` executable using ``sys.executable`` to make
104 sure the right version is used.
104 sure the right version is used.
105
105
106 For a given path ``cmd``, this returns [cmd] if cmd's extension is .exe,
106 For a given path ``cmd``, this returns [cmd] if cmd's extension is .exe,
107 .com or .bat, and [, cmd] otherwise.
107 .com or .bat, and [, cmd] otherwise.
108
108
109 Parameters
109 Parameters
110 ----------
110 ----------
111 cmd : string
111 cmd : string
112 The path of the command.
112 The path of the command.
113
113
114 Returns
114 Returns
115 -------
115 -------
116 argv-style list.
116 argv-style list.
117 """
117 """
118 ext = os.path.splitext(cmd)[1]
118 ext = os.path.splitext(cmd)[1]
119 if ext in ['.exe', '.com', '.bat']:
119 if ext in ['.exe', '.com', '.bat']:
120 return [cmd]
120 return [cmd]
121 else:
121 else:
122 if sys.platform == 'win32':
122 if sys.platform == 'win32':
123 # The -u option here turns on unbuffered output, which is required
123 # The -u option here turns on unbuffered output, which is required
124 # on Win32 to prevent wierd conflict and problems with Twisted.
124 # on Win32 to prevent wierd conflict and problems with Twisted.
125 # Also, use sys.executable to make sure we are picking up the
125 # Also, use sys.executable to make sure we are picking up the
126 # right python exe.
126 # right python exe.
127 return [sys.executable, '-u', cmd]
127 return [sys.executable, '-u', cmd]
128 else:
128 else:
129 return [sys.executable, cmd]
129 return [sys.executable, cmd]
130
130
131
131
132 def arg_split(s, posix=False):
132 def arg_split(s, posix=False):
133 """Split a command line's arguments in a shell-like manner.
133 """Split a command line's arguments in a shell-like manner.
134
134
135 This is a modified version of the standard library's shlex.split()
135 This is a modified version of the standard library's shlex.split()
136 function, but with a default of posix=False for splitting, so that quotes
136 function, but with a default of posix=False for splitting, so that quotes
137 in inputs are respected."""
137 in inputs are respected."""
138
138
139 # XXX - there may be unicode-related problems here!!! I'm not sure that
139 # Unfortunately, python's shlex module is buggy with unicode input:
140 # shlex is truly unicode-safe, so it might be necessary to do
140 # http://bugs.python.org/issue1170
141 #
141 # At least encoding the input when it's unicode seems to help, but there
142 # s = s.encode(sys.stdin.encoding)
142 # may be more problems lurking. Apparently this is fixed in python3.
143 #
143 if isinstance(s, unicode):
144 # first, to ensure that shlex gets a normal string. Input from anyone who
144 s = s.encode(sys.stdin.encoding)
145 # knows more about unicode and shlex than I would be good to have here...
146 lex = shlex.shlex(s, posix=posix)
145 lex = shlex.shlex(s, posix=posix)
147 lex.whitespace_split = True
146 lex.whitespace_split = True
148 return list(lex)
147 return list(lex)
149
148
150
149
151 def system(cmd, verbose=0, debug=0, header=''):
150 def system(cmd, verbose=0, debug=0, header=''):
152 """Execute a system command, return its exit status.
151 """Execute a system command, return its exit status.
153
152
154 Options:
153 Options:
155
154
156 - verbose (0): print the command to be executed.
155 - verbose (0): print the command to be executed.
157
156
158 - debug (0): only print, do not actually execute.
157 - debug (0): only print, do not actually execute.
159
158
160 - header (''): Header to print on screen prior to the executed command (it
159 - header (''): Header to print on screen prior to the executed command (it
161 is only prepended to the command, no newlines are added).
160 is only prepended to the command, no newlines are added).
162
161
163 Note: a stateful version of this function is available through the
162 Note: a stateful version of this function is available through the
164 SystemExec class."""
163 SystemExec class."""
165
164
166 stat = 0
165 stat = 0
167 if verbose or debug: print header+cmd
166 if verbose or debug: print header+cmd
168 sys.stdout.flush()
167 sys.stdout.flush()
169 if not debug: stat = os.system(cmd)
168 if not debug: stat = os.system(cmd)
170 return stat
169 return stat
171
170
172
171
173 def abbrev_cwd():
172 def abbrev_cwd():
174 """ Return abbreviated version of cwd, e.g. d:mydir """
173 """ Return abbreviated version of cwd, e.g. d:mydir """
175 cwd = os.getcwd().replace('\\','/')
174 cwd = os.getcwd().replace('\\','/')
176 drivepart = ''
175 drivepart = ''
177 tail = cwd
176 tail = cwd
178 if sys.platform == 'win32':
177 if sys.platform == 'win32':
179 if len(cwd) < 4:
178 if len(cwd) < 4:
180 return cwd
179 return cwd
181 drivepart,tail = os.path.splitdrive(cwd)
180 drivepart,tail = os.path.splitdrive(cwd)
182
181
183
182
184 parts = tail.split('/')
183 parts = tail.split('/')
185 if len(parts) > 2:
184 if len(parts) > 2:
186 tail = '/'.join(parts[-2:])
185 tail = '/'.join(parts[-2:])
187
186
188 return (drivepart + (
187 return (drivepart + (
189 cwd == '/' and '/' or tail))
188 cwd == '/' and '/' or tail))
190
189
191
190
192 # This function is used by ipython in a lot of places to make system calls.
191 # This function is used by ipython in a lot of places to make system calls.
193 # We need it to be slightly different under win32, due to the vagaries of
192 # We need it to be slightly different under win32, due to the vagaries of
194 # 'network shares'. A win32 override is below.
193 # 'network shares'. A win32 override is below.
195
194
196 def shell(cmd, verbose=0, debug=0, header=''):
195 def shell(cmd, verbose=0, debug=0, header=''):
197 """Execute a command in the system shell, always return None.
196 """Execute a command in the system shell, always return None.
198
197
199 Options:
198 Options:
200
199
201 - verbose (0): print the command to be executed.
200 - verbose (0): print the command to be executed.
202
201
203 - debug (0): only print, do not actually execute.
202 - debug (0): only print, do not actually execute.
204
203
205 - header (''): Header to print on screen prior to the executed command (it
204 - header (''): Header to print on screen prior to the executed command (it
206 is only prepended to the command, no newlines are added).
205 is only prepended to the command, no newlines are added).
207
206
208 Note: this is similar to system(), but it returns None so it can
207 Note: this is similar to system(), but it returns None so it can
209 be conveniently used in interactive loops without getting the return value
208 be conveniently used in interactive loops without getting the return value
210 (typically 0) printed many times."""
209 (typically 0) printed many times."""
211
210
212 stat = 0
211 stat = 0
213 if verbose or debug: print header+cmd
212 if verbose or debug: print header+cmd
214 # flush stdout so we don't mangle python's buffering
213 # flush stdout so we don't mangle python's buffering
215 sys.stdout.flush()
214 sys.stdout.flush()
216
215
217 if not debug:
216 if not debug:
218 set_term_title("IPy " + cmd)
217 set_term_title("IPy " + cmd)
219 os.system(cmd)
218 os.system(cmd)
220 set_term_title("IPy " + abbrev_cwd())
219 set_term_title("IPy " + abbrev_cwd())
221
220
222 # override shell() for win32 to deal with network shares
221 # override shell() for win32 to deal with network shares
223 if os.name in ('nt','dos'):
222 if os.name in ('nt','dos'):
224
223
225 shell_ori = shell
224 shell_ori = shell
226
225
227 def shell(cmd, verbose=0, debug=0, header=''):
226 def shell(cmd, verbose=0, debug=0, header=''):
228 if os.getcwd().startswith(r"\\"):
227 if os.getcwd().startswith(r"\\"):
229 path = os.getcwd()
228 path = os.getcwd()
230 # change to c drive (cannot be on UNC-share when issuing os.system,
229 # change to c drive (cannot be on UNC-share when issuing os.system,
231 # as cmd.exe cannot handle UNC addresses)
230 # as cmd.exe cannot handle UNC addresses)
232 os.chdir("c:")
231 os.chdir("c:")
233 # issue pushd to the UNC-share and then run the command
232 # issue pushd to the UNC-share and then run the command
234 try:
233 try:
235 shell_ori('"pushd %s&&"'%path+cmd,verbose,debug,header)
234 shell_ori('"pushd %s&&"'%path+cmd,verbose,debug,header)
236 finally:
235 finally:
237 os.chdir(path)
236 os.chdir(path)
238 else:
237 else:
239 shell_ori(cmd,verbose,debug,header)
238 shell_ori(cmd,verbose,debug,header)
240
239
241 shell.__doc__ = shell_ori.__doc__
240 shell.__doc__ = shell_ori.__doc__
242
241
243
242
244 def getoutput(cmd, verbose=0, debug=0, header='', split=0):
243 def getoutput(cmd, verbose=0, debug=0, header='', split=0):
245 """Dummy substitute for perl's backquotes.
244 """Dummy substitute for perl's backquotes.
246
245
247 Executes a command and returns the output.
246 Executes a command and returns the output.
248
247
249 Accepts the same arguments as system(), plus:
248 Accepts the same arguments as system(), plus:
250
249
251 - split(0): if true, the output is returned as a list split on newlines.
250 - split(0): if true, the output is returned as a list split on newlines.
252
251
253 Note: a stateful version of this function is available through the
252 Note: a stateful version of this function is available through the
254 SystemExec class.
253 SystemExec class.
255
254
256 This is pretty much deprecated and rarely used, getoutputerror may be
255 This is pretty much deprecated and rarely used, getoutputerror may be
257 what you need.
256 what you need.
258
257
259 """
258 """
260
259
261 if verbose or debug: print header+cmd
260 if verbose or debug: print header+cmd
262 if not debug:
261 if not debug:
263 pipe = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout
262 pipe = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout
264 output = pipe.read()
263 output = pipe.read()
265 # stipping last \n is here for backwards compat.
264 # stipping last \n is here for backwards compat.
266 if output.endswith('\n'):
265 if output.endswith('\n'):
267 output = output[:-1]
266 output = output[:-1]
268 if split:
267 if split:
269 return output.split('\n')
268 return output.split('\n')
270 else:
269 else:
271 return output
270 return output
272
271
273
272
274 # for compatibility with older naming conventions
273 # for compatibility with older naming conventions
275 xsys = system
274 xsys = system
276
275
277
276
278 def getoutputerror(cmd, verbose=0, debug=0, header='', split=0):
277 def getoutputerror(cmd, verbose=0, debug=0, header='', split=0):
279 """Return (standard output,standard error) of executing cmd in a shell.
278 """Return (standard output,standard error) of executing cmd in a shell.
280
279
281 Accepts the same arguments as system(), plus:
280 Accepts the same arguments as system(), plus:
282
281
283 - split(0): if true, each of stdout/err is returned as a list split on
282 - split(0): if true, each of stdout/err is returned as a list split on
284 newlines.
283 newlines.
285
284
286 Note: a stateful version of this function is available through the
285 Note: a stateful version of this function is available through the
287 SystemExec class."""
286 SystemExec class."""
288
287
289 if verbose or debug: print header+cmd
288 if verbose or debug: print header+cmd
290 if not cmd:
289 if not cmd:
291 if split:
290 if split:
292 return [],[]
291 return [],[]
293 else:
292 else:
294 return '',''
293 return '',''
295 if not debug:
294 if not debug:
296 p = subprocess.Popen(cmd, shell=True,
295 p = subprocess.Popen(cmd, shell=True,
297 stdin=subprocess.PIPE,
296 stdin=subprocess.PIPE,
298 stdout=subprocess.PIPE,
297 stdout=subprocess.PIPE,
299 stderr=subprocess.PIPE,
298 stderr=subprocess.PIPE,
300 close_fds=True)
299 close_fds=True)
301 pin, pout, perr = (p.stdin, p.stdout, p.stderr)
300 pin, pout, perr = (p.stdin, p.stdout, p.stderr)
302
301
303 tout = pout.read().rstrip()
302 tout = pout.read().rstrip()
304 terr = perr.read().rstrip()
303 terr = perr.read().rstrip()
305 pin.close()
304 pin.close()
306 pout.close()
305 pout.close()
307 perr.close()
306 perr.close()
308 if split:
307 if split:
309 return tout.split('\n'),terr.split('\n')
308 return tout.split('\n'),terr.split('\n')
310 else:
309 else:
311 return tout,terr
310 return tout,terr
312
311
313
312
314 class SystemExec:
313 class SystemExec:
315 """Access the system and getoutput functions through a stateful interface.
314 """Access the system and getoutput functions through a stateful interface.
316
315
317 Note: here we refer to the system and getoutput functions from this
316 Note: here we refer to the system and getoutput functions from this
318 library, not the ones from the standard python library.
317 library, not the ones from the standard python library.
319
318
320 This class offers the system and getoutput functions as methods, but the
319 This class offers the system and getoutput functions as methods, but the
321 verbose, debug and header parameters can be set for the instance (at
320 verbose, debug and header parameters can be set for the instance (at
322 creation time or later) so that they don't need to be specified on each
321 creation time or later) so that they don't need to be specified on each
323 call.
322 call.
324
323
325 For efficiency reasons, there's no way to override the parameters on a
324 For efficiency reasons, there's no way to override the parameters on a
326 per-call basis other than by setting instance attributes. If you need
325 per-call basis other than by setting instance attributes. If you need
327 local overrides, it's best to directly call system() or getoutput().
326 local overrides, it's best to directly call system() or getoutput().
328
327
329 The following names are provided as alternate options:
328 The following names are provided as alternate options:
330 - xsys: alias to system
329 - xsys: alias to system
331 - bq: alias to getoutput
330 - bq: alias to getoutput
332
331
333 An instance can then be created as:
332 An instance can then be created as:
334 >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ')
333 >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ')
335 """
334 """
336
335
337 def __init__(self, verbose=0, debug=0, header='', split=0):
336 def __init__(self, verbose=0, debug=0, header='', split=0):
338 """Specify the instance's values for verbose, debug and header."""
337 """Specify the instance's values for verbose, debug and header."""
339 self.verbose = verbose
338 self.verbose = verbose
340 self.debug = debug
339 self.debug = debug
341 self.header = header
340 self.header = header
342 self.split = split
341 self.split = split
343
342
344 def system(self, cmd):
343 def system(self, cmd):
345 """Stateful interface to system(), with the same keyword parameters."""
344 """Stateful interface to system(), with the same keyword parameters."""
346
345
347 system(cmd, self.verbose, self.debug, self.header)
346 system(cmd, self.verbose, self.debug, self.header)
348
347
349 def shell(self, cmd):
348 def shell(self, cmd):
350 """Stateful interface to shell(), with the same keyword parameters."""
349 """Stateful interface to shell(), with the same keyword parameters."""
351
350
352 shell(cmd, self.verbose, self.debug, self.header)
351 shell(cmd, self.verbose, self.debug, self.header)
353
352
354 xsys = system # alias
353 xsys = system # alias
355
354
356 def getoutput(self, cmd):
355 def getoutput(self, cmd):
357 """Stateful interface to getoutput()."""
356 """Stateful interface to getoutput()."""
358
357
359 return getoutput(cmd, self.verbose, self.debug, self.header, self.split)
358 return getoutput(cmd, self.verbose, self.debug, self.header, self.split)
360
359
361 def getoutputerror(self, cmd):
360 def getoutputerror(self, cmd):
362 """Stateful interface to getoutputerror()."""
361 """Stateful interface to getoutputerror()."""
363
362
364 return getoutputerror(cmd, self.verbose, self.debug, self.header, self.split)
363 return getoutputerror(cmd, self.verbose, self.debug, self.header, self.split)
365
364
366 bq = getoutput # alias
365 bq = getoutput # alias
367
366
368
367
@@ -1,62 +1,68 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """
2 """
3 Tests for platutils.py
3 Tests for platutils.py
4 """
4 """
5
5
6 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
7 # Copyright (C) 2008-2009 The IPython Development Team
7 # Copyright (C) 2008-2009 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 import sys
17 import sys
18
18
19 import nose.tools as nt
19 import nose.tools as nt
20
20
21 from IPython.utils.process import find_cmd, FindCmdError
21 from IPython.utils.process import find_cmd, FindCmdError, arg_split
22 from IPython.testing import decorators as dec
22 from IPython.testing import decorators as dec
23
23
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25 # Tests
25 # Tests
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27
27
28 def test_find_cmd_python():
28 def test_find_cmd_python():
29 """Make sure we find sys.exectable for python."""
29 """Make sure we find sys.exectable for python."""
30 nt.assert_equals(find_cmd('python'), sys.executable)
30 nt.assert_equals(find_cmd('python'), sys.executable)
31
31
32
32
33 @dec.skip_win32
33 @dec.skip_win32
34 def test_find_cmd_ls():
34 def test_find_cmd_ls():
35 """Make sure we can find the full path to ls."""
35 """Make sure we can find the full path to ls."""
36 path = find_cmd('ls')
36 path = find_cmd('ls')
37 nt.assert_true(path.endswith('ls'))
37 nt.assert_true(path.endswith('ls'))
38
38
39
39
40 def has_pywin32():
40 def has_pywin32():
41 try:
41 try:
42 import win32api
42 import win32api
43 except ImportError:
43 except ImportError:
44 return False
44 return False
45 return True
45 return True
46
46
47
47
48 @dec.onlyif(has_pywin32, "This test requires win32api to run")
48 @dec.onlyif(has_pywin32, "This test requires win32api to run")
49 def test_find_cmd_pythonw():
49 def test_find_cmd_pythonw():
50 """Try to find pythonw on Windows."""
50 """Try to find pythonw on Windows."""
51 path = find_cmd('pythonw')
51 path = find_cmd('pythonw')
52 nt.assert_true(path.endswith('pythonw.exe'))
52 nt.assert_true(path.endswith('pythonw.exe'))
53
53
54
54
55 @dec.onlyif(lambda : sys.platform != 'win32' or has_pywin32(),
55 @dec.onlyif(lambda : sys.platform != 'win32' or has_pywin32(),
56 "This test runs on posix or in win32 with win32api installed")
56 "This test runs on posix or in win32 with win32api installed")
57 def test_find_cmd_fail():
57 def test_find_cmd_fail():
58 """Make sure that FindCmdError is raised if we can't find the cmd."""
58 """Make sure that FindCmdError is raised if we can't find the cmd."""
59 nt.assert_raises(FindCmdError,find_cmd,'asdfasdf')
59 nt.assert_raises(FindCmdError,find_cmd,'asdfasdf')
60
60
61
61
62
62 def test_arg_split():
63 """Ensure that argument lines are correctly split like in a shell."""
64 tests = [['hi', ['hi']],
65 [u'hi', [u'hi']],
66 ]
67 for argstr, argv in tests:
68 nt.assert_equal(arg_split(argstr), argv)
@@ -1,100 +1,117 b''
1 # -*- coding: UTF-8 -*-
1 """Some tests for the wildcard utilities."""
2 import sys, unittest
3 sys.path.append ('..')
4
2
5 from IPython import wildcard
3 #-----------------------------------------------------------------------------
4 # Library imports
5 #-----------------------------------------------------------------------------
6 # Stdlib
7 import sys
8 import unittest
9
10 # Our own
11 from IPython.utils import wildcard
12
13 #-----------------------------------------------------------------------------
14 # Globals for test
15 #-----------------------------------------------------------------------------
6
16
7 class obj_t(object):
17 class obj_t(object):
8 pass
18 pass
9
19
10 root=obj_t()
20 root = obj_t()
11 l=["arna","abel","ABEL","active","bob","bark","abbot"]
21 l = ["arna","abel","ABEL","active","bob","bark","abbot"]
12 q=["kate","loop","arne","vito","lucifer","koppel"]
22 q = ["kate","loop","arne","vito","lucifer","koppel"]
13 for x in l:
23 for x in l:
14 o=obj_t()
24 o = obj_t()
15 setattr(root,x,o)
25 setattr(root,x,o)
16 for y in q:
26 for y in q:
17 p=obj_t()
27 p = obj_t()
18 setattr(o,y,p)
28 setattr(o,y,p)
19 root._apan=obj_t()
29 root._apan = obj_t()
20 root._apan.a=10
30 root._apan.a = 10
21 root._apan._a=20
31 root._apan._a = 20
22 root._apan.__a=20
32 root._apan.__a = 20
23 root.__anka=obj_t()
33 root.__anka = obj_t()
24 root.__anka.a=10
34 root.__anka.a = 10
25 root.__anka._a=20
35 root.__anka._a = 20
26 root.__anka.__a=20
36 root.__anka.__a = 20
37
38 root._APAN = obj_t()
39 root._APAN.a = 10
40 root._APAN._a = 20
41 root._APAN.__a = 20
42 root.__ANKA = obj_t()
43 root.__ANKA.a = 10
44 root.__ANKA._a = 20
45 root.__ANKA.__a = 20
27
46
28 root._APAN=obj_t()
47 #-----------------------------------------------------------------------------
29 root._APAN.a=10
48 # Test cases
30 root._APAN._a=20
49 #-----------------------------------------------------------------------------
31 root._APAN.__a=20
32 root.__ANKA=obj_t()
33 root.__ANKA.a=10
34 root.__ANKA._a=20
35 root.__ANKA.__a=20
36
50
37 class Tests (unittest.TestCase):
51 class Tests (unittest.TestCase):
38 def test_case(self):
52 def test_case(self):
39 ns=root.__dict__
53 ns=root.__dict__
40 tests=[
54 tests=[
41 ("a*", ["abbot","abel","active","arna",]),
55 ("a*", ["abbot","abel","active","arna",]),
42 ("?b*.?o*",["abbot.koppel","abbot.loop","abel.koppel","abel.loop",]),
56 ("?b*.?o*",["abbot.koppel","abbot.loop","abel.koppel","abel.loop",]),
43 ("_a*", []),
57 ("_a*", []),
44 ("_*anka", ["__anka",]),
58 ("_*anka", ["__anka",]),
45 ("_*a*", ["__anka",]),
59 ("_*a*", ["__anka",]),
46 ]
60 ]
47 for pat,res in tests:
61 for pat,res in tests:
48 res.sort()
62 res.sort()
49 a=wildcard.list_namespace(ns,"all",pat,ignore_case=False,show_all=False).keys()
63 a=wildcard.list_namespace(ns,"all",pat,ignore_case=False,
64 show_all=False).keys()
50 a.sort()
65 a.sort()
51 self.assertEqual(a,res)
66 self.assertEqual(a,res)
52
67
53 def test_case_showall(self):
68 def test_case_showall(self):
54 ns=root.__dict__
69 ns=root.__dict__
55 tests=[
70 tests=[
56 ("a*", ["abbot","abel","active","arna",]),
71 ("a*", ["abbot","abel","active","arna",]),
57 ("?b*.?o*",["abbot.koppel","abbot.loop","abel.koppel","abel.loop",]),
72 ("?b*.?o*",["abbot.koppel","abbot.loop","abel.koppel","abel.loop",]),
58 ("_a*", ["_apan"]),
73 ("_a*", ["_apan"]),
59 ("_*anka", ["__anka",]),
74 ("_*anka", ["__anka",]),
60 ("_*a*", ["__anka","_apan",]),
75 ("_*a*", ["__anka","_apan",]),
61 ]
76 ]
62 for pat,res in tests:
77 for pat,res in tests:
63 res.sort()
78 res.sort()
64 a=wildcard.list_namespace(ns,"all",pat,ignore_case=False,show_all=True).keys()
79 a=wildcard.list_namespace(ns,"all",pat,ignore_case=False,
80 show_all=True).keys()
65 a.sort()
81 a.sort()
66 self.assertEqual(a,res)
82 self.assertEqual(a,res)
67
83
68
84
69 def test_nocase(self):
85 def test_nocase(self):
70 ns=root.__dict__
86 ns=root.__dict__
71 tests=[
87 tests=[
72 ("a*", ["abbot","abel","ABEL","active","arna",]),
88 ("a*", ["abbot","abel","ABEL","active","arna",]),
73 ("?b*.?o*",["abbot.koppel","abbot.loop","abel.koppel","abel.loop","ABEL.koppel","ABEL.loop",]),
89 ("?b*.?o*",["abbot.koppel","abbot.loop","abel.koppel","abel.loop",
90 "ABEL.koppel","ABEL.loop",]),
74 ("_a*", []),
91 ("_a*", []),
75 ("_*anka", ["__anka","__ANKA",]),
92 ("_*anka", ["__anka","__ANKA",]),
76 ("_*a*", ["__anka","__ANKA",]),
93 ("_*a*", ["__anka","__ANKA",]),
77 ]
94 ]
78 for pat,res in tests:
95 for pat,res in tests:
79 res.sort()
96 res.sort()
80 a=wildcard.list_namespace(ns,"all",pat,ignore_case=True,show_all=False).keys()
97 a=wildcard.list_namespace(ns,"all",pat,ignore_case=True,
98 show_all=False).keys()
81 a.sort()
99 a.sort()
82 self.assertEqual(a,res)
100 self.assertEqual(a,res)
83
101
84 def test_nocase_showall(self):
102 def test_nocase_showall(self):
85 ns=root.__dict__
103 ns=root.__dict__
86 tests=[
104 tests=[
87 ("a*", ["abbot","abel","ABEL","active","arna",]),
105 ("a*", ["abbot","abel","ABEL","active","arna",]),
88 ("?b*.?o*",["abbot.koppel","abbot.loop","abel.koppel","abel.loop","ABEL.koppel","ABEL.loop",]),
106 ("?b*.?o*",["abbot.koppel","abbot.loop","abel.koppel","abel.loop",
107 "ABEL.koppel","ABEL.loop",]),
89 ("_a*", ["_apan","_APAN"]),
108 ("_a*", ["_apan","_APAN"]),
90 ("_*anka", ["__anka","__ANKA",]),
109 ("_*anka", ["__anka","__ANKA",]),
91 ("_*a*", ["__anka","__ANKA","_apan","_APAN"]),
110 ("_*a*", ["__anka","__ANKA","_apan","_APAN"]),
92 ]
111 ]
93 for pat,res in tests:
112 for pat,res in tests:
94 res.sort()
113 res.sort()
95 a=wildcard.list_namespace(ns,"all",pat,ignore_case=True,show_all=True).keys()
114 a=wildcard.list_namespace(ns,"all",pat,ignore_case=True,
115 show_all=True).keys()
96 a.sort()
116 a.sort()
97 self.assertEqual(a,res)
117 self.assertEqual(a,res)
98
99 if __name__ == '__main__':
100 unittest.main() No newline at end of file
@@ -1,323 +1,313 b''
1 # encoding: utf-8
1 # encoding: utf-8
2
2
3 """
3 """
4 This module defines the things that are used in setup.py for building IPython
4 This module defines the things that are used in setup.py for building IPython
5
5
6 This includes:
6 This includes:
7
7
8 * The basic arguments to setup
8 * The basic arguments to setup
9 * Functions for finding things like packages, package data, etc.
9 * Functions for finding things like packages, package data, etc.
10 * A function for checking dependencies.
10 * A function for checking dependencies.
11 """
11 """
12
12
13 __docformat__ = "restructuredtext en"
13 __docformat__ = "restructuredtext en"
14
14
15 #-------------------------------------------------------------------------------
15 #-------------------------------------------------------------------------------
16 # Copyright (C) 2008 The IPython Development Team
16 # Copyright (C) 2008 The IPython Development Team
17 #
17 #
18 # Distributed under the terms of the BSD License. The full license is in
18 # Distributed under the terms of the BSD License. The full license is in
19 # the file COPYING, distributed as part of this software.
19 # the file COPYING, distributed as part of this software.
20 #-------------------------------------------------------------------------------
20 #-------------------------------------------------------------------------------
21
21
22 #-------------------------------------------------------------------------------
22 #-------------------------------------------------------------------------------
23 # Imports
23 # Imports
24 #-------------------------------------------------------------------------------
24 #-------------------------------------------------------------------------------
25
25
26 import os, sys
26 import os, sys
27
27
28 from glob import glob
28 from glob import glob
29
29
30 from setupext import install_data_ext
30 from setupext import install_data_ext
31
31
32 #-------------------------------------------------------------------------------
32 #-------------------------------------------------------------------------------
33 # Useful globals and utility functions
33 # Useful globals and utility functions
34 #-------------------------------------------------------------------------------
34 #-------------------------------------------------------------------------------
35
35
36 # A few handy globals
36 # A few handy globals
37 isfile = os.path.isfile
37 isfile = os.path.isfile
38 pjoin = os.path.join
38 pjoin = os.path.join
39
39
40 def oscmd(s):
40 def oscmd(s):
41 print ">", s
41 print ">", s
42 os.system(s)
42 os.system(s)
43
43
44 # A little utility we'll need below, since glob() does NOT allow you to do
44 # A little utility we'll need below, since glob() does NOT allow you to do
45 # exclusion on multiple endings!
45 # exclusion on multiple endings!
46 def file_doesnt_endwith(test,endings):
46 def file_doesnt_endwith(test,endings):
47 """Return true if test is a file and its name does NOT end with any
47 """Return true if test is a file and its name does NOT end with any
48 of the strings listed in endings."""
48 of the strings listed in endings."""
49 if not isfile(test):
49 if not isfile(test):
50 return False
50 return False
51 for e in endings:
51 for e in endings:
52 if test.endswith(e):
52 if test.endswith(e):
53 return False
53 return False
54 return True
54 return True
55
55
56 #---------------------------------------------------------------------------
56 #---------------------------------------------------------------------------
57 # Basic project information
57 # Basic project information
58 #---------------------------------------------------------------------------
58 #---------------------------------------------------------------------------
59
59
60 # release.py contains version, authors, license, url, keywords, etc.
60 # release.py contains version, authors, license, url, keywords, etc.
61 execfile(pjoin('IPython','core','release.py'))
61 execfile(pjoin('IPython','core','release.py'))
62
62
63 # Create a dict with the basic information
63 # Create a dict with the basic information
64 # This dict is eventually passed to setup after additional keys are added.
64 # This dict is eventually passed to setup after additional keys are added.
65 setup_args = dict(
65 setup_args = dict(
66 name = name,
66 name = name,
67 version = version,
67 version = version,
68 description = description,
68 description = description,
69 long_description = long_description,
69 long_description = long_description,
70 author = author,
70 author = author,
71 author_email = author_email,
71 author_email = author_email,
72 url = url,
72 url = url,
73 download_url = download_url,
73 download_url = download_url,
74 license = license,
74 license = license,
75 platforms = platforms,
75 platforms = platforms,
76 keywords = keywords,
76 keywords = keywords,
77 cmdclass = {'install_data': install_data_ext},
77 cmdclass = {'install_data': install_data_ext},
78 )
78 )
79
79
80
80
81 #---------------------------------------------------------------------------
81 #---------------------------------------------------------------------------
82 # Find packages
82 # Find packages
83 #---------------------------------------------------------------------------
83 #---------------------------------------------------------------------------
84
84
85 def add_package(packages,pname,config=False,tests=False,scripts=False,
85 def add_package(packages,pname,config=False,tests=False,scripts=False,
86 others=None):
86 others=None):
87 """
87 """
88 Add a package to the list of packages, including certain subpackages.
88 Add a package to the list of packages, including certain subpackages.
89 """
89 """
90 packages.append('.'.join(['IPython',pname]))
90 packages.append('.'.join(['IPython',pname]))
91 if config:
91 if config:
92 packages.append('.'.join(['IPython',pname,'config']))
92 packages.append('.'.join(['IPython',pname,'config']))
93 if tests:
93 if tests:
94 packages.append('.'.join(['IPython',pname,'tests']))
94 packages.append('.'.join(['IPython',pname,'tests']))
95 if scripts:
95 if scripts:
96 packages.append('.'.join(['IPython',pname,'scripts']))
96 packages.append('.'.join(['IPython',pname,'scripts']))
97 if others is not None:
97 if others is not None:
98 for o in others:
98 for o in others:
99 packages.append('.'.join(['IPython',pname,o]))
99 packages.append('.'.join(['IPython',pname,o]))
100
100
101 def find_packages():
101 def find_packages():
102 """
102 """
103 Find all of IPython's packages.
103 Find all of IPython's packages.
104 """
104 """
105 packages = ['IPython']
105 packages = ['IPython']
106 add_package(packages, 'config', tests=True, others=['default','profile'])
106 add_package(packages, 'config', tests=True, others=['default','profile'])
107 add_package(packages, 'core', tests=True)
107 add_package(packages, 'core', tests=True)
108 add_package(packages, 'deathrow', tests=True)
108 add_package(packages, 'deathrow', tests=True)
109 add_package(packages, 'extensions')
109 add_package(packages, 'extensions')
110 add_package(packages, 'external')
110 add_package(packages, 'external')
111 add_package(packages, 'frontend', tests=True)
111 add_package(packages, 'frontend')
112 # Don't include the cocoa frontend for now as it is not stable
113 if sys.platform == 'darwin' and False:
114 add_package(packages, 'frontend.cocoa', tests=True, others=['plugin'])
115 add_package(packages, 'frontend.cocoa.examples')
116 add_package(packages, 'frontend.cocoa.examples.IPython1Sandbox')
117 add_package(packages, 'frontend.cocoa.examples.IPython1Sandbox.English.lproj')
118 add_package(packages, 'frontend.process')
119 add_package(packages, 'frontend.qt')
112 add_package(packages, 'frontend.qt')
120 add_package(packages, 'frontend.qt.console')
113 add_package(packages, 'frontend.qt.console')
121 add_package(packages, 'frontend.wx')
122 add_package(packages, 'gui')
123 add_package(packages, 'gui.wx')
124 add_package(packages, 'kernel', config=False, tests=True, scripts=True)
114 add_package(packages, 'kernel', config=False, tests=True, scripts=True)
125 add_package(packages, 'kernel.core', config=False, tests=True)
115 add_package(packages, 'kernel.core', config=False, tests=True)
126 add_package(packages, 'lib', tests=True)
116 add_package(packages, 'lib', tests=True)
127 add_package(packages, 'quarantine', tests=True)
117 add_package(packages, 'quarantine', tests=True)
128 add_package(packages, 'scripts')
118 add_package(packages, 'scripts')
129 add_package(packages, 'testing', tests=True)
119 add_package(packages, 'testing', tests=True)
130 add_package(packages, 'testing.plugin', tests=False)
120 add_package(packages, 'testing.plugin', tests=False)
131 add_package(packages, 'utils', tests=True)
121 add_package(packages, 'utils', tests=True)
132 add_package(packages, 'zmq')
122 add_package(packages, 'zmq')
133 return packages
123 return packages
134
124
135 #---------------------------------------------------------------------------
125 #---------------------------------------------------------------------------
136 # Find package data
126 # Find package data
137 #---------------------------------------------------------------------------
127 #---------------------------------------------------------------------------
138
128
139 def find_package_data():
129 def find_package_data():
140 """
130 """
141 Find IPython's package_data.
131 Find IPython's package_data.
142 """
132 """
143 # This is not enough for these things to appear in an sdist.
133 # This is not enough for these things to appear in an sdist.
144 # We need to muck with the MANIFEST to get this to work
134 # We need to muck with the MANIFEST to get this to work
145 package_data = {
135 package_data = {
146 'IPython.config.userconfig' : ['*'],
136 'IPython.config.userconfig' : ['*'],
147 'IPython.testing' : ['*.txt']
137 'IPython.testing' : ['*.txt']
148 }
138 }
149 return package_data
139 return package_data
150
140
151
141
152 #---------------------------------------------------------------------------
142 #---------------------------------------------------------------------------
153 # Find data files
143 # Find data files
154 #---------------------------------------------------------------------------
144 #---------------------------------------------------------------------------
155
145
156 def make_dir_struct(tag,base,out_base):
146 def make_dir_struct(tag,base,out_base):
157 """Make the directory structure of all files below a starting dir.
147 """Make the directory structure of all files below a starting dir.
158
148
159 This is just a convenience routine to help build a nested directory
149 This is just a convenience routine to help build a nested directory
160 hierarchy because distutils is too stupid to do this by itself.
150 hierarchy because distutils is too stupid to do this by itself.
161
151
162 XXX - this needs a proper docstring!
152 XXX - this needs a proper docstring!
163 """
153 """
164
154
165 # we'll use these a lot below
155 # we'll use these a lot below
166 lbase = len(base)
156 lbase = len(base)
167 pathsep = os.path.sep
157 pathsep = os.path.sep
168 lpathsep = len(pathsep)
158 lpathsep = len(pathsep)
169
159
170 out = []
160 out = []
171 for (dirpath,dirnames,filenames) in os.walk(base):
161 for (dirpath,dirnames,filenames) in os.walk(base):
172 # we need to strip out the dirpath from the base to map it to the
162 # we need to strip out the dirpath from the base to map it to the
173 # output (installation) path. This requires possibly stripping the
163 # output (installation) path. This requires possibly stripping the
174 # path separator, because otherwise pjoin will not work correctly
164 # path separator, because otherwise pjoin will not work correctly
175 # (pjoin('foo/','/bar') returns '/bar').
165 # (pjoin('foo/','/bar') returns '/bar').
176
166
177 dp_eff = dirpath[lbase:]
167 dp_eff = dirpath[lbase:]
178 if dp_eff.startswith(pathsep):
168 if dp_eff.startswith(pathsep):
179 dp_eff = dp_eff[lpathsep:]
169 dp_eff = dp_eff[lpathsep:]
180 # The output path must be anchored at the out_base marker
170 # The output path must be anchored at the out_base marker
181 out_path = pjoin(out_base,dp_eff)
171 out_path = pjoin(out_base,dp_eff)
182 # Now we can generate the final filenames. Since os.walk only produces
172 # Now we can generate the final filenames. Since os.walk only produces
183 # filenames, we must join back with the dirpath to get full valid file
173 # filenames, we must join back with the dirpath to get full valid file
184 # paths:
174 # paths:
185 pfiles = [pjoin(dirpath,f) for f in filenames]
175 pfiles = [pjoin(dirpath,f) for f in filenames]
186 # Finally, generate the entry we need, which is a triple of (tag,output
176 # Finally, generate the entry we need, which is a triple of (tag,output
187 # path, files) for use as a data_files parameter in install_data.
177 # path, files) for use as a data_files parameter in install_data.
188 out.append((tag,out_path,pfiles))
178 out.append((tag,out_path,pfiles))
189
179
190 return out
180 return out
191
181
192
182
193 def find_data_files():
183 def find_data_files():
194 """
184 """
195 Find IPython's data_files.
185 Find IPython's data_files.
196
186
197 Most of these are docs.
187 Most of these are docs.
198 """
188 """
199
189
200 docdirbase = pjoin('share', 'doc', 'ipython')
190 docdirbase = pjoin('share', 'doc', 'ipython')
201 manpagebase = pjoin('share', 'man', 'man1')
191 manpagebase = pjoin('share', 'man', 'man1')
202
192
203 # Simple file lists can be made by hand
193 # Simple file lists can be made by hand
204 manpages = filter(isfile, glob(pjoin('docs','man','*.1.gz')))
194 manpages = filter(isfile, glob(pjoin('docs','man','*.1.gz')))
205 igridhelpfiles = filter(isfile, glob(pjoin('IPython','extensions','igrid_help.*')))
195 igridhelpfiles = filter(isfile, glob(pjoin('IPython','extensions','igrid_help.*')))
206
196
207 # For nested structures, use the utility above
197 # For nested structures, use the utility above
208 example_files = make_dir_struct(
198 example_files = make_dir_struct(
209 'data',
199 'data',
210 pjoin('docs','examples'),
200 pjoin('docs','examples'),
211 pjoin(docdirbase,'examples')
201 pjoin(docdirbase,'examples')
212 )
202 )
213 manual_files = make_dir_struct(
203 manual_files = make_dir_struct(
214 'data',
204 'data',
215 pjoin('docs','dist'),
205 pjoin('docs','dist'),
216 pjoin(docdirbase,'manual')
206 pjoin(docdirbase,'manual')
217 )
207 )
218
208
219 # And assemble the entire output list
209 # And assemble the entire output list
220 data_files = [ ('data',manpagebase, manpages),
210 data_files = [ ('data',manpagebase, manpages),
221 ('data',pjoin(docdirbase,'extensions'),igridhelpfiles),
211 ('data',pjoin(docdirbase,'extensions'),igridhelpfiles),
222 ] + manual_files + example_files
212 ] + manual_files + example_files
223
213
224 ## import pprint # dbg
214 ## import pprint # dbg
225 ## print '*'*80
215 ## print '*'*80
226 ## print 'data files'
216 ## print 'data files'
227 ## pprint.pprint(data_files)
217 ## pprint.pprint(data_files)
228 ## print '*'*80
218 ## print '*'*80
229
219
230 return data_files
220 return data_files
231
221
232
222
233 def make_man_update_target(manpage):
223 def make_man_update_target(manpage):
234 """Return a target_update-compliant tuple for the given manpage.
224 """Return a target_update-compliant tuple for the given manpage.
235
225
236 Parameters
226 Parameters
237 ----------
227 ----------
238 manpage : string
228 manpage : string
239 Name of the manpage, must include the section number (trailing number).
229 Name of the manpage, must include the section number (trailing number).
240
230
241 Example
231 Example
242 -------
232 -------
243
233
244 >>> make_man_update_target('ipython.1') #doctest: +NORMALIZE_WHITESPACE
234 >>> make_man_update_target('ipython.1') #doctest: +NORMALIZE_WHITESPACE
245 ('docs/man/ipython.1.gz',
235 ('docs/man/ipython.1.gz',
246 ['docs/man/ipython.1'],
236 ['docs/man/ipython.1'],
247 'cd docs/man && gzip -9c ipython.1 > ipython.1.gz')
237 'cd docs/man && gzip -9c ipython.1 > ipython.1.gz')
248 """
238 """
249 man_dir = pjoin('docs', 'man')
239 man_dir = pjoin('docs', 'man')
250 manpage_gz = manpage + '.gz'
240 manpage_gz = manpage + '.gz'
251 manpath = pjoin(man_dir, manpage)
241 manpath = pjoin(man_dir, manpage)
252 manpath_gz = pjoin(man_dir, manpage_gz)
242 manpath_gz = pjoin(man_dir, manpage_gz)
253 gz_cmd = ( "cd %(man_dir)s && gzip -9c %(manpage)s > %(manpage_gz)s" %
243 gz_cmd = ( "cd %(man_dir)s && gzip -9c %(manpage)s > %(manpage_gz)s" %
254 locals() )
244 locals() )
255 return (manpath_gz, [manpath], gz_cmd)
245 return (manpath_gz, [manpath], gz_cmd)
256
246
257 #---------------------------------------------------------------------------
247 #---------------------------------------------------------------------------
258 # Find scripts
248 # Find scripts
259 #---------------------------------------------------------------------------
249 #---------------------------------------------------------------------------
260
250
261 def find_scripts():
251 def find_scripts():
262 """
252 """
263 Find IPython's scripts.
253 Find IPython's scripts.
264 """
254 """
265 kernel_scripts = pjoin('IPython','kernel','scripts')
255 kernel_scripts = pjoin('IPython','kernel','scripts')
266 main_scripts = pjoin('IPython','scripts')
256 main_scripts = pjoin('IPython','scripts')
267 scripts = [pjoin(kernel_scripts, 'ipengine'),
257 scripts = [pjoin(kernel_scripts, 'ipengine'),
268 pjoin(kernel_scripts, 'ipcontroller'),
258 pjoin(kernel_scripts, 'ipcontroller'),
269 pjoin(kernel_scripts, 'ipcluster'),
259 pjoin(kernel_scripts, 'ipcluster'),
270 pjoin(main_scripts, 'ipython'),
260 pjoin(main_scripts, 'ipython'),
271 pjoin(main_scripts, 'ipythonx'),
261 pjoin(main_scripts, 'ipythonx'),
272 pjoin(main_scripts, 'ipython-wx'),
262 pjoin(main_scripts, 'ipython-wx'),
273 pjoin(main_scripts, 'pycolor'),
263 pjoin(main_scripts, 'pycolor'),
274 pjoin(main_scripts, 'irunner'),
264 pjoin(main_scripts, 'irunner'),
275 pjoin(main_scripts, 'iptest')
265 pjoin(main_scripts, 'iptest')
276 ]
266 ]
277
267
278 # Script to be run by the windows binary installer after the default setup
268 # Script to be run by the windows binary installer after the default setup
279 # routine, to add shortcuts and similar windows-only things. Windows
269 # routine, to add shortcuts and similar windows-only things. Windows
280 # post-install scripts MUST reside in the scripts/ dir, otherwise distutils
270 # post-install scripts MUST reside in the scripts/ dir, otherwise distutils
281 # doesn't find them.
271 # doesn't find them.
282 if 'bdist_wininst' in sys.argv:
272 if 'bdist_wininst' in sys.argv:
283 if len(sys.argv) > 2 and ('sdist' in sys.argv or 'bdist_rpm' in sys.argv):
273 if len(sys.argv) > 2 and ('sdist' in sys.argv or 'bdist_rpm' in sys.argv):
284 print >> sys.stderr,"ERROR: bdist_wininst must be run alone. Exiting."
274 print >> sys.stderr,"ERROR: bdist_wininst must be run alone. Exiting."
285 sys.exit(1)
275 sys.exit(1)
286 scripts.append(pjoin('scripts','ipython_win_post_install.py'))
276 scripts.append(pjoin('scripts','ipython_win_post_install.py'))
287
277
288 return scripts
278 return scripts
289
279
290 #---------------------------------------------------------------------------
280 #---------------------------------------------------------------------------
291 # Verify all dependencies
281 # Verify all dependencies
292 #---------------------------------------------------------------------------
282 #---------------------------------------------------------------------------
293
283
294 def check_for_dependencies():
284 def check_for_dependencies():
295 """Check for IPython's dependencies.
285 """Check for IPython's dependencies.
296
286
297 This function should NOT be called if running under setuptools!
287 This function should NOT be called if running under setuptools!
298 """
288 """
299 from setupext.setupext import (
289 from setupext.setupext import (
300 print_line, print_raw, print_status, print_message,
290 print_line, print_raw, print_status, print_message,
301 check_for_zopeinterface, check_for_twisted,
291 check_for_zopeinterface, check_for_twisted,
302 check_for_foolscap, check_for_pyopenssl,
292 check_for_foolscap, check_for_pyopenssl,
303 check_for_sphinx, check_for_pygments,
293 check_for_sphinx, check_for_pygments,
304 check_for_nose, check_for_pexpect
294 check_for_nose, check_for_pexpect
305 )
295 )
306 print_line()
296 print_line()
307 print_raw("BUILDING IPYTHON")
297 print_raw("BUILDING IPYTHON")
308 print_status('python', sys.version)
298 print_status('python', sys.version)
309 print_status('platform', sys.platform)
299 print_status('platform', sys.platform)
310 if sys.platform == 'win32':
300 if sys.platform == 'win32':
311 print_status('Windows version', sys.getwindowsversion())
301 print_status('Windows version', sys.getwindowsversion())
312
302
313 print_raw("")
303 print_raw("")
314 print_raw("OPTIONAL DEPENDENCIES")
304 print_raw("OPTIONAL DEPENDENCIES")
315
305
316 check_for_zopeinterface()
306 check_for_zopeinterface()
317 check_for_twisted()
307 check_for_twisted()
318 check_for_foolscap()
308 check_for_foolscap()
319 check_for_pyopenssl()
309 check_for_pyopenssl()
320 check_for_sphinx()
310 check_for_sphinx()
321 check_for_pygments()
311 check_for_pygments()
322 check_for_nose()
312 check_for_nose()
323 check_for_pexpect()
313 check_for_pexpect()
1 NO CONTENT: file was removed
NO CONTENT: file was removed
1 NO CONTENT: file was removed
NO CONTENT: file was removed
1 NO CONTENT: file was removed
NO CONTENT: file was removed
1 NO CONTENT: file was removed
NO CONTENT: file was removed
1 NO CONTENT: file was removed
NO CONTENT: file was removed
1 NO CONTENT: file was removed
NO CONTENT: file was removed
1 NO CONTENT: file was removed
NO CONTENT: file was removed
1 NO CONTENT: file was removed
NO CONTENT: file was removed
1 NO CONTENT: file was removed
NO CONTENT: file was removed
1 NO CONTENT: file was removed
NO CONTENT: file was removed
General Comments 0
You need to be logged in to leave comments. Login now