##// END OF EJS Templates
ipy_which.py added (%which magic)...
vivainio -
Show More

The requested changes are too big and content was truncated. Show full diff

@@ -0,0 +1,70 b''
1 r""" %which magic command
2
3 %which <cmd> => search PATH for files matching PATH. Also scans aliases
4
5 """
6
7 import IPython.ipapi
8 ip = IPython.ipapi.get()
9
10 import os,sys
11 from fnmatch import fnmatch
12 def which(fname):
13 fullpath = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
14
15 if '.' not in fullpath:
16 fullpath = ['.'] + fullpath
17 fn = fname
18 for p in fullpath:
19 for f in os.listdir(p):
20 head, ext = os.path.splitext(f)
21 if f == fn or fnmatch(head, fn):
22 yield os.path.join(p,f)
23 return
24
25 def which_alias(fname):
26 for al, tgt in ip.IP.alias_table.items():
27 if not (al == fname or fnmatch(al, fname)):
28 continue
29 trg = tgt[1]
30
31 trans = ip.expand_alias(trg)
32 cmd = trans.split(None,1)[0]
33 print al,"->",trans
34 for realcmd in which(cmd):
35 print " ==",realcmd
36
37 def which_f(self, arg):
38 r""" %which <cmd> => search PATH for files matching cmd. Also scans aliases.
39
40 Traverses PATH and prints all files (not just executables!) that match the
41 pattern on command line. Probably more useful in finding stuff
42 interactively than 'which', which only prints the first matching item.
43
44 Also discovers and expands aliases, so you'll see what will be executed
45 when you call an alias.
46
47 Example:
48
49 [~]|62> %which d
50 d -> ls -F --color=auto
51 == c:\cygwin\bin\ls.exe
52 c:\cygwin\bin\d.exe
53
54 [~]|64> %which diff*
55 diff3 -> diff3
56 == c:\cygwin\bin\diff3.exe
57 diff -> diff
58 == c:\cygwin\bin\diff.exe
59 c:\cygwin\bin\diff.exe
60 c:\cygwin\bin\diff3.exe
61
62 """
63
64 which_alias(arg)
65
66 for e in which(arg):
67 print e
68
69 ip.expose_magic("which",which_f)
70
@@ -1,187 +1,188 b''
1 """Shell mode for IPython.
1 """Shell mode for IPython.
2
2
3 Start ipython in shell mode by invoking "ipython -p sh"
3 Start ipython in shell mode by invoking "ipython -p sh"
4
4
5 (the old version, "ipython -p pysh" still works but this is the more "modern"
5 (the old version, "ipython -p pysh" still works but this is the more "modern"
6 shell mode and is recommended for users who don't care about pysh-mode
6 shell mode and is recommended for users who don't care about pysh-mode
7 compatibility)
7 compatibility)
8 """
8 """
9
9
10 from IPython import ipapi
10 from IPython import ipapi
11 import os,textwrap
11 import os,textwrap
12
12
13 # The import below effectively obsoletes your old-style ipythonrc[.ini],
13 # The import below effectively obsoletes your old-style ipythonrc[.ini],
14 # so consider yourself warned!
14 # so consider yourself warned!
15
15
16 import ipy_defaults
16 import ipy_defaults
17
17
18 def main():
18 def main():
19 ip = ipapi.get()
19 ip = ipapi.get()
20 o = ip.options
20 o = ip.options
21 # autocall to "full" mode (smart mode is default, I like full mode)
21 # autocall to "full" mode (smart mode is default, I like full mode)
22
22
23 o.autocall = 2
23 o.autocall = 2
24
24
25 # Jason Orendorff's path class is handy to have in user namespace
25 # Jason Orendorff's path class is handy to have in user namespace
26 # if you are doing shell-like stuff
26 # if you are doing shell-like stuff
27 try:
27 try:
28 ip.ex("from path import path" )
28 ip.ex("from path import path" )
29 except ImportError:
29 except ImportError:
30 pass
30 pass
31
31
32 # beefed up %env is handy in shell mode
32 # beefed up %env is handy in shell mode
33 import envpersist
33 import envpersist
34 import ipy_which
34
35
35
36
36 ip.ex('import os')
37 ip.ex('import os')
37 ip.ex("def up(): os.chdir('..')")
38 ip.ex("def up(): os.chdir('..')")
38
39
39 # Get pysh-like prompt for all profiles.
40 # Get pysh-like prompt for all profiles.
40
41
41 o.prompt_in1= '\C_LightBlue[\C_LightCyan\Y1\C_LightBlue]\C_Green|\#> '
42 o.prompt_in1= '\C_LightBlue[\C_LightCyan\Y1\C_LightBlue]\C_Green|\#> '
42 o.prompt_in2= '\C_Green|\C_LightGreen\D\C_Green> '
43 o.prompt_in2= '\C_Green|\C_LightGreen\D\C_Green> '
43 o.prompt_out= '<\#> '
44 o.prompt_out= '<\#> '
44
45
45 from IPython import Release
46 from IPython import Release
46
47
47 import sys
48 import sys
48 # I like my banner minimal.
49 # I like my banner minimal.
49 o.banner = "Py %s IPy %s\n" % (sys.version.split('\n')[0],Release.version)
50 o.banner = "Py %s IPy %s\n" % (sys.version.split('\n')[0],Release.version)
50
51
51 # make 'd' an alias for ls -F
52 # make 'd' an alias for ls -F
52
53
53 ip.magic('alias d ls -F --color=auto')
54 ip.magic('alias d ls -F --color=auto')
54
55
55 ip.IP.default_option('cd','-q')
56 ip.IP.default_option('cd','-q')
56
57
57 # If you only rarely want to execute the things you %edit...
58 # If you only rarely want to execute the things you %edit...
58
59
59 #ip.IP.default_option('edit','-x')
60 #ip.IP.default_option('edit','-x')
60
61
61
62
62 o.prompts_pad_left="1"
63 o.prompts_pad_left="1"
63 # Remove all blank lines in between prompts, like a normal shell.
64 # Remove all blank lines in between prompts, like a normal shell.
64 o.separate_in="0"
65 o.separate_in="0"
65 o.separate_out="0"
66 o.separate_out="0"
66 o.separate_out2="0"
67 o.separate_out2="0"
67
68
68 # now alias all syscommands
69 # now alias all syscommands
69
70
70 db = ip.db
71 db = ip.db
71
72
72 syscmds = db.get("syscmdlist",[] )
73 syscmds = db.get("syscmdlist",[] )
73 if not syscmds:
74 if not syscmds:
74 print textwrap.dedent("""
75 print textwrap.dedent("""
75 System command list not initialized, probably the first run...
76 System command list not initialized, probably the first run...
76 running %rehashx to refresh the command list. Run %rehashx
77 running %rehashx to refresh the command list. Run %rehashx
77 again to refresh command list (after installing new software etc.)
78 again to refresh command list (after installing new software etc.)
78 """)
79 """)
79 ip.magic('rehashx')
80 ip.magic('rehashx')
80 syscmds = db.get("syscmdlist")
81 syscmds = db.get("syscmdlist")
81 for cmd in syscmds:
82 for cmd in syscmds:
82 #print "al",cmd
83 #print "al",cmd
83 noext, ext = os.path.splitext(cmd)
84 noext, ext = os.path.splitext(cmd)
84 ip.IP.alias_table[noext] = (0,cmd)
85 ip.IP.alias_table[noext] = (0,cmd)
85 extend_shell_behavior(ip)
86 extend_shell_behavior(ip)
86
87
87 def extend_shell_behavior(ip):
88 def extend_shell_behavior(ip):
88
89
89 # Instead of making signature a global variable tie it to IPSHELL.
90 # Instead of making signature a global variable tie it to IPSHELL.
90 # In future if it is required to distinguish between different
91 # In future if it is required to distinguish between different
91 # shells we can assign a signature per shell basis
92 # shells we can assign a signature per shell basis
92 ip.IP.__sig__ = 0xa005
93 ip.IP.__sig__ = 0xa005
93 # mark the IPSHELL with this signature
94 # mark the IPSHELL with this signature
94 ip.IP.user_ns['__builtins__'].__dict__['__sig__'] = ip.IP.__sig__
95 ip.IP.user_ns['__builtins__'].__dict__['__sig__'] = ip.IP.__sig__
95
96
96 from IPython.Itpl import ItplNS
97 from IPython.Itpl import ItplNS
97 from IPython.genutils import shell
98 from IPython.genutils import shell
98 # utility to expand user variables via Itpl
99 # utility to expand user variables via Itpl
99 # xxx do something sensible with depth?
100 # xxx do something sensible with depth?
100 ip.IP.var_expand = lambda cmd, lvars=None, depth=2: \
101 ip.IP.var_expand = lambda cmd, lvars=None, depth=2: \
101 str(ItplNS(cmd.replace('#','\#'), ip.IP.user_ns, get_locals()))
102 str(ItplNS(cmd.replace('#','\#'), ip.IP.user_ns, get_locals()))
102
103
103 def get_locals():
104 def get_locals():
104 """ Substituting a variable through Itpl deep inside the IPSHELL stack
105 """ Substituting a variable through Itpl deep inside the IPSHELL stack
105 requires the knowledge of all the variables in scope upto the last
106 requires the knowledge of all the variables in scope upto the last
106 IPSHELL frame. This routine simply merges all the local variables
107 IPSHELL frame. This routine simply merges all the local variables
107 on the IPSHELL stack without worrying about their scope rules
108 on the IPSHELL stack without worrying about their scope rules
108 """
109 """
109 import sys
110 import sys
110 # note lambda expression constitues a function call
111 # note lambda expression constitues a function call
111 # hence fno should be incremented by one
112 # hence fno should be incremented by one
112 getsig = lambda fno: sys._getframe(fno+1).f_globals \
113 getsig = lambda fno: sys._getframe(fno+1).f_globals \
113 ['__builtins__'].__dict__['__sig__']
114 ['__builtins__'].__dict__['__sig__']
114 getlvars = lambda fno: sys._getframe(fno+1).f_locals
115 getlvars = lambda fno: sys._getframe(fno+1).f_locals
115 # trackback until we enter the IPSHELL
116 # trackback until we enter the IPSHELL
116 frame_no = 1
117 frame_no = 1
117 sig = ip.IP.__sig__
118 sig = ip.IP.__sig__
118 fsig = ~sig
119 fsig = ~sig
119 while fsig != sig :
120 while fsig != sig :
120 try:
121 try:
121 fsig = getsig(frame_no)
122 fsig = getsig(frame_no)
122 except (AttributeError, KeyError):
123 except (AttributeError, KeyError):
123 frame_no += 1
124 frame_no += 1
124 except ValueError:
125 except ValueError:
125 # stack is depleted
126 # stack is depleted
126 # call did not originate from IPSHELL
127 # call did not originate from IPSHELL
127 return {}
128 return {}
128 first_frame = frame_no
129 first_frame = frame_no
129 # walk further back until we exit from IPSHELL or deplete stack
130 # walk further back until we exit from IPSHELL or deplete stack
130 try:
131 try:
131 while(sig == getsig(frame_no+1)):
132 while(sig == getsig(frame_no+1)):
132 frame_no += 1
133 frame_no += 1
133 except (AttributeError, KeyError, ValueError):
134 except (AttributeError, KeyError, ValueError):
134 pass
135 pass
135 # merge the locals from top down hence overriding
136 # merge the locals from top down hence overriding
136 # any re-definitions of variables, functions etc.
137 # any re-definitions of variables, functions etc.
137 lvars = {}
138 lvars = {}
138 for fno in range(frame_no, first_frame-1, -1):
139 for fno in range(frame_no, first_frame-1, -1):
139 lvars.update(getlvars(fno))
140 lvars.update(getlvars(fno))
140 #print '\n'*5, first_frame, frame_no, '\n', lvars, '\n'*5 #dbg
141 #print '\n'*5, first_frame, frame_no, '\n', lvars, '\n'*5 #dbg
141 return lvars
142 return lvars
142
143
143 def _runlines(lines):
144 def _runlines(lines):
144 """Run a string of one or more lines of source.
145 """Run a string of one or more lines of source.
145
146
146 This method is capable of running a string containing multiple source
147 This method is capable of running a string containing multiple source
147 lines, as if they had been entered at the IPython prompt. Since it
148 lines, as if they had been entered at the IPython prompt. Since it
148 exposes IPython's processing machinery, the given strings can contain
149 exposes IPython's processing machinery, the given strings can contain
149 magic calls (%magic), special shell access (!cmd), etc."""
150 magic calls (%magic), special shell access (!cmd), etc."""
150
151
151 # We must start with a clean buffer, in case this is run from an
152 # We must start with a clean buffer, in case this is run from an
152 # interactive IPython session (via a magic, for example).
153 # interactive IPython session (via a magic, for example).
153 ip.IP.resetbuffer()
154 ip.IP.resetbuffer()
154 lines = lines.split('\n')
155 lines = lines.split('\n')
155 more = 0
156 more = 0
156 command = ''
157 command = ''
157 for line in lines:
158 for line in lines:
158 # skip blank lines so we don't mess up the prompt counter, but do
159 # skip blank lines so we don't mess up the prompt counter, but do
159 # NOT skip even a blank line if we are in a code block (more is
160 # NOT skip even a blank line if we are in a code block (more is
160 # true)
161 # true)
161 # if command is not empty trim the line
162 # if command is not empty trim the line
162 if command != '' :
163 if command != '' :
163 line = line.strip()
164 line = line.strip()
164 # add the broken line to the command
165 # add the broken line to the command
165 if line and line[-1] == '\\' :
166 if line and line[-1] == '\\' :
166 command += line[0:-1] + ' '
167 command += line[0:-1] + ' '
167 more = True
168 more = True
168 continue
169 continue
169 else :
170 else :
170 # add the last (current) line to the command
171 # add the last (current) line to the command
171 command += line
172 command += line
172 if command or more:
173 if command or more:
173 more = ip.IP.push(ip.IP.prefilter(command,more))
174 more = ip.IP.push(ip.IP.prefilter(command,more))
174 command = ''
175 command = ''
175 # IPython's runsource returns None if there was an error
176 # IPython's runsource returns None if there was an error
176 # compiling the code. This allows us to stop processing right
177 # compiling the code. This allows us to stop processing right
177 # away, so the user gets the error message at the right place.
178 # away, so the user gets the error message at the right place.
178 if more is None:
179 if more is None:
179 break
180 break
180 # final newline in case the input didn't have it, so that the code
181 # final newline in case the input didn't have it, so that the code
181 # actually does get executed
182 # actually does get executed
182 if more:
183 if more:
183 ip.IP.push('\n')
184 ip.IP.push('\n')
184
185
185 ip.IP.runlines = _runlines
186 ip.IP.runlines = _runlines
186
187
187 main()
188 main()
@@ -1,405 +1,406 b''
1 ''' IPython customization API
1 ''' IPython customization API
2
2
3 Your one-stop module for configuring & extending ipython
3 Your one-stop module for configuring & extending ipython
4
4
5 The API will probably break when ipython 1.0 is released, but so
5 The API will probably break when ipython 1.0 is released, but so
6 will the other configuration method (rc files).
6 will the other configuration method (rc files).
7
7
8 All names prefixed by underscores are for internal use, not part
8 All names prefixed by underscores are for internal use, not part
9 of the public api.
9 of the public api.
10
10
11 Below is an example that you can just put to a module and import from ipython.
11 Below is an example that you can just put to a module and import from ipython.
12
12
13 A good practice is to install the config script below as e.g.
13 A good practice is to install the config script below as e.g.
14
14
15 ~/.ipython/my_private_conf.py
15 ~/.ipython/my_private_conf.py
16
16
17 And do
17 And do
18
18
19 import_mod my_private_conf
19 import_mod my_private_conf
20
20
21 in ~/.ipython/ipythonrc
21 in ~/.ipython/ipythonrc
22
22
23 That way the module is imported at startup and you can have all your
23 That way the module is imported at startup and you can have all your
24 personal configuration (as opposed to boilerplate ipythonrc-PROFILENAME
24 personal configuration (as opposed to boilerplate ipythonrc-PROFILENAME
25 stuff) in there.
25 stuff) in there.
26
26
27 -----------------------------------------------
27 -----------------------------------------------
28 import IPython.ipapi
28 import IPython.ipapi
29 ip = IPython.ipapi.get()
29 ip = IPython.ipapi.get()
30
30
31 def ankka_f(self, arg):
31 def ankka_f(self, arg):
32 print "Ankka",self,"says uppercase:",arg.upper()
32 print "Ankka",self,"says uppercase:",arg.upper()
33
33
34 ip.expose_magic("ankka",ankka_f)
34 ip.expose_magic("ankka",ankka_f)
35
35
36 ip.magic('alias sayhi echo "Testing, hi ok"')
36 ip.magic('alias sayhi echo "Testing, hi ok"')
37 ip.magic('alias helloworld echo "Hello world"')
37 ip.magic('alias helloworld echo "Hello world"')
38 ip.system('pwd')
38 ip.system('pwd')
39
39
40 ip.ex('import re')
40 ip.ex('import re')
41 ip.ex("""
41 ip.ex("""
42 def funcci(a,b):
42 def funcci(a,b):
43 print a+b
43 print a+b
44 print funcci(3,4)
44 print funcci(3,4)
45 """)
45 """)
46 ip.ex("funcci(348,9)")
46 ip.ex("funcci(348,9)")
47
47
48 def jed_editor(self,filename, linenum=None):
48 def jed_editor(self,filename, linenum=None):
49 print "Calling my own editor, jed ... via hook!"
49 print "Calling my own editor, jed ... via hook!"
50 import os
50 import os
51 if linenum is None: linenum = 0
51 if linenum is None: linenum = 0
52 os.system('jed +%d %s' % (linenum, filename))
52 os.system('jed +%d %s' % (linenum, filename))
53 print "exiting jed"
53 print "exiting jed"
54
54
55 ip.set_hook('editor',jed_editor)
55 ip.set_hook('editor',jed_editor)
56
56
57 o = ip.options
57 o = ip.options
58 o.autocall = 2 # FULL autocall mode
58 o.autocall = 2 # FULL autocall mode
59
59
60 print "done!"
60 print "done!"
61 '''
61 '''
62
62
63 # stdlib imports
63 # stdlib imports
64 import __builtin__
64 import __builtin__
65 import sys
65 import sys
66
66
67 # our own
67 # our own
68 from IPython.genutils import warn,error
68 from IPython.genutils import warn,error
69
69
70 class TryNext(Exception):
70 class TryNext(Exception):
71 """Try next hook exception.
71 """Try next hook exception.
72
72
73 Raise this in your hook function to indicate that the next hook handler
73 Raise this in your hook function to indicate that the next hook handler
74 should be used to handle the operation. If you pass arguments to the
74 should be used to handle the operation. If you pass arguments to the
75 constructor those arguments will be used by the next hook instead of the
75 constructor those arguments will be used by the next hook instead of the
76 original ones.
76 original ones.
77 """
77 """
78
78
79 def __init__(self, *args, **kwargs):
79 def __init__(self, *args, **kwargs):
80 self.args = args
80 self.args = args
81 self.kwargs = kwargs
81 self.kwargs = kwargs
82
82
83 # contains the most recently instantiated IPApi
83 # contains the most recently instantiated IPApi
84
84
85 class IPythonNotRunning:
85 class IPythonNotRunning:
86 """Dummy do-nothing class.
86 """Dummy do-nothing class.
87
87
88 Instances of this class return a dummy attribute on all accesses, which
88 Instances of this class return a dummy attribute on all accesses, which
89 can be called and warns. This makes it easier to write scripts which use
89 can be called and warns. This makes it easier to write scripts which use
90 the ipapi.get() object for informational purposes to operate both with and
90 the ipapi.get() object for informational purposes to operate both with and
91 without ipython. Obviously code which uses the ipython object for
91 without ipython. Obviously code which uses the ipython object for
92 computations will not work, but this allows a wider range of code to
92 computations will not work, but this allows a wider range of code to
93 transparently work whether ipython is being used or not."""
93 transparently work whether ipython is being used or not."""
94
94
95 def __init__(self,warn=True):
95 def __init__(self,warn=True):
96 if warn:
96 if warn:
97 self.dummy = self._dummy_warn
97 self.dummy = self._dummy_warn
98 else:
98 else:
99 self.dummy = self._dummy_silent
99 self.dummy = self._dummy_silent
100
100
101 def __str__(self):
101 def __str__(self):
102 return "<IPythonNotRunning>"
102 return "<IPythonNotRunning>"
103
103
104 __repr__ = __str__
104 __repr__ = __str__
105
105
106 def __getattr__(self,name):
106 def __getattr__(self,name):
107 return self.dummy
107 return self.dummy
108
108
109 def _dummy_warn(self,*args,**kw):
109 def _dummy_warn(self,*args,**kw):
110 """Dummy function, which doesn't do anything but warn."""
110 """Dummy function, which doesn't do anything but warn."""
111
111
112 warn("IPython is not running, this is a dummy no-op function")
112 warn("IPython is not running, this is a dummy no-op function")
113
113
114 def _dummy_silent(self,*args,**kw):
114 def _dummy_silent(self,*args,**kw):
115 """Dummy function, which doesn't do anything and emits no warnings."""
115 """Dummy function, which doesn't do anything and emits no warnings."""
116 pass
116 pass
117
117
118 _recent = None
118 _recent = None
119
119
120
120
121 def get(allow_dummy=False,dummy_warn=True):
121 def get(allow_dummy=False,dummy_warn=True):
122 """Get an IPApi object.
122 """Get an IPApi object.
123
123
124 If allow_dummy is true, returns an instance of IPythonNotRunning
124 If allow_dummy is true, returns an instance of IPythonNotRunning
125 instead of None if not running under IPython.
125 instead of None if not running under IPython.
126
126
127 If dummy_warn is false, the dummy instance will be completely silent.
127 If dummy_warn is false, the dummy instance will be completely silent.
128
128
129 Running this should be the first thing you do when writing extensions that
129 Running this should be the first thing you do when writing extensions that
130 can be imported as normal modules. You can then direct all the
130 can be imported as normal modules. You can then direct all the
131 configuration operations against the returned object.
131 configuration operations against the returned object.
132 """
132 """
133 global _recent
133 global _recent
134 if allow_dummy and not _recent:
134 if allow_dummy and not _recent:
135 _recent = IPythonNotRunning(dummy_warn)
135 _recent = IPythonNotRunning(dummy_warn)
136 return _recent
136 return _recent
137
137
138 class IPApi:
138 class IPApi:
139 """ The actual API class for configuring IPython
139 """ The actual API class for configuring IPython
140
140
141 You should do all of the IPython configuration by getting an IPApi object
141 You should do all of the IPython configuration by getting an IPApi object
142 with IPython.ipapi.get() and using the attributes and methods of the
142 with IPython.ipapi.get() and using the attributes and methods of the
143 returned object."""
143 returned object."""
144
144
145 def __init__(self,ip):
145 def __init__(self,ip):
146
146
147 # All attributes exposed here are considered to be the public API of
147 # All attributes exposed here are considered to be the public API of
148 # IPython. As needs dictate, some of these may be wrapped as
148 # IPython. As needs dictate, some of these may be wrapped as
149 # properties.
149 # properties.
150
150
151 self.magic = ip.ipmagic
151 self.magic = ip.ipmagic
152
152
153 self.system = ip.ipsystem
153 self.system = ip.ipsystem
154
154
155 self.set_hook = ip.set_hook
155 self.set_hook = ip.set_hook
156
156
157 self.set_custom_exc = ip.set_custom_exc
157 self.set_custom_exc = ip.set_custom_exc
158
158
159 self.user_ns = ip.user_ns
159 self.user_ns = ip.user_ns
160
160
161 self.set_crash_handler = ip.set_crash_handler
161 self.set_crash_handler = ip.set_crash_handler
162
162
163 # Session-specific data store, which can be used to store
163 # Session-specific data store, which can be used to store
164 # data that should persist through the ipython session.
164 # data that should persist through the ipython session.
165 self.meta = ip.meta
165 self.meta = ip.meta
166
166
167 # The ipython instance provided
167 # The ipython instance provided
168 self.IP = ip
168 self.IP = ip
169
169
170 global _recent
170 global _recent
171 _recent = self
171 _recent = self
172
172
173 # Use a property for some things which are added to the instance very
173 # Use a property for some things which are added to the instance very
174 # late. I don't have time right now to disentangle the initialization
174 # late. I don't have time right now to disentangle the initialization
175 # order issues, so a property lets us delay item extraction while
175 # order issues, so a property lets us delay item extraction while
176 # providing a normal attribute API.
176 # providing a normal attribute API.
177 def get_db(self):
177 def get_db(self):
178 """A handle to persistent dict-like database (a PickleShareDB object)"""
178 """A handle to persistent dict-like database (a PickleShareDB object)"""
179 return self.IP.db
179 return self.IP.db
180
180
181 db = property(get_db,None,None,get_db.__doc__)
181 db = property(get_db,None,None,get_db.__doc__)
182
182
183 def get_options(self):
183 def get_options(self):
184 """All configurable variables."""
184 """All configurable variables."""
185
185
186 # catch typos by disabling new attribute creation. If new attr creation
186 # catch typos by disabling new attribute creation. If new attr creation
187 # is in fact wanted (e.g. when exposing new options), do allow_new_attr(True)
187 # is in fact wanted (e.g. when exposing new options), do allow_new_attr(True)
188 # for the received rc struct.
188 # for the received rc struct.
189
189
190 self.IP.rc.allow_new_attr(False)
190 self.IP.rc.allow_new_attr(False)
191 return self.IP.rc
191 return self.IP.rc
192
192
193 options = property(get_options,None,None,get_options.__doc__)
193 options = property(get_options,None,None,get_options.__doc__)
194
194
195 def expose_magic(self,magicname, func):
195 def expose_magic(self,magicname, func):
196 ''' Expose own function as magic function for ipython
196 ''' Expose own function as magic function for ipython
197
197
198 def foo_impl(self,parameter_s=''):
198 def foo_impl(self,parameter_s=''):
199 """My very own magic!. (Use docstrings, IPython reads them)."""
199 """My very own magic!. (Use docstrings, IPython reads them)."""
200 print 'Magic function. Passed parameter is between < >: <'+parameter_s+'>'
200 print 'Magic function. Passed parameter is between < >: <'+parameter_s+'>'
201 print 'The self object is:',self
201 print 'The self object is:',self
202
202
203 ipapi.expose_magic("foo",foo_impl)
203 ipapi.expose_magic("foo",foo_impl)
204 '''
204 '''
205
205
206 import new
206 import new
207 im = new.instancemethod(func,self.IP, self.IP.__class__)
207 im = new.instancemethod(func,self.IP, self.IP.__class__)
208 setattr(self.IP, "magic_" + magicname, im)
208 setattr(self.IP, "magic_" + magicname, im)
209
209
210 def ex(self,cmd):
210 def ex(self,cmd):
211 """ Execute a normal python statement in user namespace """
211 """ Execute a normal python statement in user namespace """
212 exec cmd in self.user_ns
212 exec cmd in self.user_ns
213
213
214 def ev(self,expr):
214 def ev(self,expr):
215 """ Evaluate python expression expr in user namespace
215 """ Evaluate python expression expr in user namespace
216
216
217 Returns the result of evaluation"""
217 Returns the result of evaluation"""
218 return eval(expr,self.user_ns)
218 return eval(expr,self.user_ns)
219
219
220 def runlines(self,lines):
220 def runlines(self,lines):
221 """ Run the specified lines in interpreter, honoring ipython directives.
221 """ Run the specified lines in interpreter, honoring ipython directives.
222
222
223 This allows %magic and !shell escape notations.
223 This allows %magic and !shell escape notations.
224
224
225 Takes either all lines in one string or list of lines.
225 Takes either all lines in one string or list of lines.
226 """
226 """
227 if isinstance(lines,basestring):
227 if isinstance(lines,basestring):
228 self.IP.runlines(lines)
228 self.IP.runlines(lines)
229 else:
229 else:
230 self.IP.runlines('\n'.join(lines))
230 self.IP.runlines('\n'.join(lines))
231
231
232 def to_user_ns(self,vars):
232 def to_user_ns(self,vars):
233 """Inject a group of variables into the IPython user namespace.
233 """Inject a group of variables into the IPython user namespace.
234
234
235 Inputs:
235 Inputs:
236
236
237 - vars: string with variable names separated by whitespace
237 - vars: string with variable names separated by whitespace
238
238
239 This utility routine is meant to ease interactive debugging work,
239 This utility routine is meant to ease interactive debugging work,
240 where you want to easily propagate some internal variable in your code
240 where you want to easily propagate some internal variable in your code
241 up to the interactive namespace for further exploration.
241 up to the interactive namespace for further exploration.
242
242
243 When you run code via %run, globals in your script become visible at
243 When you run code via %run, globals in your script become visible at
244 the interactive prompt, but this doesn't happen for locals inside your
244 the interactive prompt, but this doesn't happen for locals inside your
245 own functions and methods. Yet when debugging, it is common to want
245 own functions and methods. Yet when debugging, it is common to want
246 to explore some internal variables further at the interactive propmt.
246 to explore some internal variables further at the interactive propmt.
247
247
248 Examples:
248 Examples:
249
249
250 To use this, you first must obtain a handle on the ipython object as
250 To use this, you first must obtain a handle on the ipython object as
251 indicated above, via:
251 indicated above, via:
252
252
253 import IPython.ipapi
253 import IPython.ipapi
254 ip = IPython.ipapi.get()
254 ip = IPython.ipapi.get()
255
255
256 Once this is done, inside a routine foo() where you want to expose
256 Once this is done, inside a routine foo() where you want to expose
257 variables x and y, you do the following:
257 variables x and y, you do the following:
258
258
259 def foo():
259 def foo():
260 ...
260 ...
261 x = your_computation()
261 x = your_computation()
262 y = something_else()
262 y = something_else()
263
263
264 # This pushes x and y to the interactive prompt immediately, even
264 # This pushes x and y to the interactive prompt immediately, even
265 # if this routine crashes on the next line after:
265 # if this routine crashes on the next line after:
266 ip.to_user_ns('x y')
266 ip.to_user_ns('x y')
267 ...
267 ...
268 # return
268 # return
269
269
270 If you need to rename variables, just use ip.user_ns with dict
270 If you need to rename variables, just use ip.user_ns with dict
271 and update:
271 and update:
272
272
273 # exposes variables 'foo' as 'x' and 'bar' as 'y' in IPython
273 # exposes variables 'foo' as 'x' and 'bar' as 'y' in IPython
274 # user namespace
274 # user namespace
275 ip.user_ns.update(dict(x=foo,y=bar))
275 ip.user_ns.update(dict(x=foo,y=bar))
276 """
276 """
277
277
278 # print 'vars given:',vars # dbg
278 # print 'vars given:',vars # dbg
279 # Get the caller's frame to evaluate the given names in
279 # Get the caller's frame to evaluate the given names in
280 cf = sys._getframe(1)
280 cf = sys._getframe(1)
281
281
282 user_ns = self.user_ns
282 user_ns = self.user_ns
283
283
284 for name in vars.split():
284 for name in vars.split():
285 try:
285 try:
286 user_ns[name] = eval(name,cf.f_globals,cf.f_locals)
286 user_ns[name] = eval(name,cf.f_globals,cf.f_locals)
287 except:
287 except:
288 error('could not get var. %s from %s' %
288 error('could not get var. %s from %s' %
289 (name,cf.f_code.co_name))
289 (name,cf.f_code.co_name))
290
290
291 def expand_alias(self,line):
291 def expand_alias(self,line):
292 """ Expand an alias in the command line
292 """ Expand an alias in the command line
293
293
294 Returns the provided command line, possibly with the first word
294 Returns the provided command line, possibly with the first word
295 (command) translated according to alias expansion rules.
295 (command) translated according to alias expansion rules.
296
296
297 [ipython]|16> _ip.expand_aliases("np myfile.txt")
297 [ipython]|16> _ip.expand_aliases("np myfile.txt")
298 <16> 'q:/opt/np/notepad++.exe myfile.txt'
298 <16> 'q:/opt/np/notepad++.exe myfile.txt'
299 """
299 """
300
300
301 pre,fn,rest = self.IP.split_user_input(line)
301 pre,fn,rest = self.IP.split_user_input(line)
302 res = pre + self.IP.expand_aliases(fn,rest)
302 res = pre + self.IP.expand_aliases(fn,rest)
303 return res
303
304
304 def defalias(self, name, cmd):
305 def defalias(self, name, cmd):
305 """ Define a new alias
306 """ Define a new alias
306
307
307 _ip.defalias('bb','bldmake bldfiles')
308 _ip.defalias('bb','bldmake bldfiles')
308
309
309 Creates a new alias named 'bb' in ipython user namespace
310 Creates a new alias named 'bb' in ipython user namespace
310 """
311 """
311
312
312
313
313 nargs = cmd.count('%s')
314 nargs = cmd.count('%s')
314 if nargs>0 and cmd.find('%l')>=0:
315 if nargs>0 and cmd.find('%l')>=0:
315 raise Exception('The %s and %l specifiers are mutually exclusive '
316 raise Exception('The %s and %l specifiers are mutually exclusive '
316 'in alias definitions.')
317 'in alias definitions.')
317
318
318 else: # all looks OK
319 else: # all looks OK
319 self.IP.alias_table[name] = (nargs,cmd)
320 self.IP.alias_table[name] = (nargs,cmd)
320
321
321 def defmacro(self, *args):
322 def defmacro(self, *args):
322 """ Define a new macro
323 """ Define a new macro
323
324
324 2 forms of calling:
325 2 forms of calling:
325
326
326 mac = _ip.defmacro('print "hello"\nprint "world"')
327 mac = _ip.defmacro('print "hello"\nprint "world"')
327
328
328 (doesn't put the created macro on user namespace)
329 (doesn't put the created macro on user namespace)
329
330
330 _ip.defmacro('build', 'bldmake bldfiles\nabld build winscw udeb')
331 _ip.defmacro('build', 'bldmake bldfiles\nabld build winscw udeb')
331
332
332 (creates a macro named 'build' in user namespace)
333 (creates a macro named 'build' in user namespace)
333 """
334 """
334
335
335 import IPython.macro
336 import IPython.macro
336
337
337 if len(args) == 1:
338 if len(args) == 1:
338 return IPython.macro.Macro(args[0])
339 return IPython.macro.Macro(args[0])
339 elif len(args) == 2:
340 elif len(args) == 2:
340 self.user_ns[args[0]] = IPython.macro.Macro(args[1])
341 self.user_ns[args[0]] = IPython.macro.Macro(args[1])
341 else:
342 else:
342 return Exception("_ip.defmacro must be called with 1 or 2 arguments")
343 return Exception("_ip.defmacro must be called with 1 or 2 arguments")
343
344
344
345
345
346
346 def launch_new_instance(user_ns = None):
347 def launch_new_instance(user_ns = None):
347 """ Make and start a new ipython instance.
348 """ Make and start a new ipython instance.
348
349
349 This can be called even without having an already initialized
350 This can be called even without having an already initialized
350 ipython session running.
351 ipython session running.
351
352
352 This is also used as the egg entry point for the 'ipython' script.
353 This is also used as the egg entry point for the 'ipython' script.
353
354
354 """
355 """
355 ses = make_session(user_ns)
356 ses = make_session(user_ns)
356 ses.mainloop()
357 ses.mainloop()
357
358
358
359
359 def make_user_ns(user_ns = None):
360 def make_user_ns(user_ns = None):
360 """Return a valid user interactive namespace.
361 """Return a valid user interactive namespace.
361
362
362 This builds a dict with the minimal information needed to operate as a
363 This builds a dict with the minimal information needed to operate as a
363 valid IPython user namespace, which you can pass to the various embedding
364 valid IPython user namespace, which you can pass to the various embedding
364 classes in ipython.
365 classes in ipython.
365 """
366 """
366
367
367 if user_ns is None:
368 if user_ns is None:
368 # Set __name__ to __main__ to better match the behavior of the
369 # Set __name__ to __main__ to better match the behavior of the
369 # normal interpreter.
370 # normal interpreter.
370 user_ns = {'__name__' :'__main__',
371 user_ns = {'__name__' :'__main__',
371 '__builtins__' : __builtin__,
372 '__builtins__' : __builtin__,
372 }
373 }
373 else:
374 else:
374 user_ns.setdefault('__name__','__main__')
375 user_ns.setdefault('__name__','__main__')
375 user_ns.setdefault('__builtins__',__builtin__)
376 user_ns.setdefault('__builtins__',__builtin__)
376
377
377 return user_ns
378 return user_ns
378
379
379
380
380 def make_user_global_ns(ns = None):
381 def make_user_global_ns(ns = None):
381 """Return a valid user global namespace.
382 """Return a valid user global namespace.
382
383
383 Similar to make_user_ns(), but global namespaces are really only needed in
384 Similar to make_user_ns(), but global namespaces are really only needed in
384 embedded applications, where there is a distinction between the user's
385 embedded applications, where there is a distinction between the user's
385 interactive namespace and the global one where ipython is running."""
386 interactive namespace and the global one where ipython is running."""
386
387
387 if ns is None: ns = {}
388 if ns is None: ns = {}
388 return ns
389 return ns
389
390
390
391
391 def make_session(user_ns = None):
392 def make_session(user_ns = None):
392 """Makes, but does not launch an IPython session.
393 """Makes, but does not launch an IPython session.
393
394
394 Later on you can call obj.mainloop() on the returned object.
395 Later on you can call obj.mainloop() on the returned object.
395
396
396 Inputs:
397 Inputs:
397
398
398 - user_ns(None): a dict to be used as the user's namespace with initial
399 - user_ns(None): a dict to be used as the user's namespace with initial
399 data.
400 data.
400
401
401 WARNING: This should *not* be run when a session exists already."""
402 WARNING: This should *not* be run when a session exists already."""
402
403
403 import IPython
404 import IPython
404 return IPython.Shell.start(user_ns)
405 return IPython.Shell.start(user_ns)
405
406
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
General Comments 0
You need to be logged in to leave comments. Login now