Show More
The requested changes are too big and content was truncated. Show full diff
@@ -1,258 +1,258 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 IPython.external.path import path" ) |
|
28 | ip.ex("from IPython.external.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 |
|
34 | |||
35 | # To see where mycmd resides (in path/aliases), do %which mycmd |
|
35 | # To see where mycmd resides (in path/aliases), do %which mycmd | |
36 | import ipy_which |
|
36 | import ipy_which | |
37 |
|
37 | |||
38 | # tab completers for hg, svn, ... |
|
38 | # tab completers for hg, svn, ... | |
39 | import ipy_app_completers |
|
39 | import ipy_app_completers | |
40 |
|
40 | |||
41 | # To make executables foo and bar in mybin usable without PATH change, do: |
|
41 | # To make executables foo and bar in mybin usable without PATH change, do: | |
42 | # %rehashdir c:/mybin |
|
42 | # %rehashdir c:/mybin | |
43 | # %store foo |
|
43 | # %store foo | |
44 | # %store bar |
|
44 | # %store bar | |
45 | import ipy_rehashdir |
|
45 | import ipy_rehashdir | |
46 |
|
46 | |||
47 | # does not work without subprocess module! |
|
47 | # does not work without subprocess module! | |
48 | #import ipy_signals |
|
48 | #import ipy_signals | |
49 |
|
49 | |||
50 | ip.ex('import os') |
|
50 | ip.ex('import os') | |
51 | ip.ex("def up(): os.chdir('..')") |
|
51 | ip.ex("def up(): os.chdir('..')") | |
52 | ip.user_ns['LA'] = LastArgFinder() |
|
52 | ip.user_ns['LA'] = LastArgFinder() | |
53 | # Nice prompt |
|
53 | # Nice prompt | |
54 |
|
54 | |||
55 | o.prompt_in1= r'\C_LightBlue[\C_LightCyan\Y2\C_LightBlue]\C_Green|\#> ' |
|
55 | o.prompt_in1= r'\C_LightBlue[\C_LightCyan\Y2\C_LightBlue]\C_Green|\#> ' | |
56 | o.prompt_in2= r'\C_Green|\C_LightGreen\D\C_Green> ' |
|
56 | o.prompt_in2= r'\C_Green|\C_LightGreen\D\C_Green> ' | |
57 | o.prompt_out= '<\#> ' |
|
57 | o.prompt_out= '<\#> ' | |
58 |
|
58 | |||
59 | from IPython import Release |
|
59 | from IPython import Release | |
60 |
|
60 | |||
61 | import sys |
|
61 | import sys | |
62 | # Non-chatty banner |
|
62 | # Non-chatty banner | |
63 | o.banner = "IPython %s [on Py %s]\n" % (Release.version,sys.version.split(None,1)[0]) |
|
63 | o.banner = "IPython %s [on Py %s]\n" % (Release.version,sys.version.split(None,1)[0]) | |
64 |
|
64 | |||
65 |
|
65 | |||
66 | ip.IP.default_option('cd','-q') |
|
66 | ip.IP.default_option('cd','-q') | |
67 | ip.IP.default_option('macro', '-r') |
|
67 | ip.IP.default_option('macro', '-r') | |
68 | # If you only rarely want to execute the things you %edit... |
|
68 | # If you only rarely want to execute the things you %edit... | |
69 | #ip.IP.default_option('edit','-x') |
|
69 | #ip.IP.default_option('edit','-x') | |
70 |
|
70 | |||
71 |
|
71 | |||
72 | o.prompts_pad_left="1" |
|
72 | o.prompts_pad_left="1" | |
73 | # Remove all blank lines in between prompts, like a normal shell. |
|
73 | # Remove all blank lines in between prompts, like a normal shell. | |
74 | o.separate_in="0" |
|
74 | o.separate_in="0" | |
75 | o.separate_out="0" |
|
75 | o.separate_out="0" | |
76 | o.separate_out2="0" |
|
76 | o.separate_out2="0" | |
77 |
|
77 | |||
78 | # now alias all syscommands |
|
78 | # now alias all syscommands | |
79 |
|
79 | |||
80 | db = ip.db |
|
80 | db = ip.db | |
81 |
|
81 | |||
82 | syscmds = db.get("syscmdlist",[] ) |
|
82 | syscmds = db.get("syscmdlist",[] ) | |
83 | if not syscmds: |
|
83 | if not syscmds: | |
84 | print textwrap.dedent(""" |
|
84 | print textwrap.dedent(""" | |
85 | System command list not initialized, probably the first run... |
|
85 | System command list not initialized, probably the first run... | |
86 | running %rehashx to refresh the command list. Run %rehashx |
|
86 | running %rehashx to refresh the command list. Run %rehashx | |
87 | again to refresh command list (after installing new software etc.) |
|
87 | again to refresh command list (after installing new software etc.) | |
88 | """) |
|
88 | """) | |
89 | ip.magic('rehashx') |
|
89 | ip.magic('rehashx') | |
90 | syscmds = db.get("syscmdlist") |
|
90 | syscmds = db.get("syscmdlist") | |
91 |
|
91 | |||
92 | # lowcase aliases on win32 only |
|
92 | # lowcase aliases on win32 only | |
93 | if os.name == 'posix': |
|
93 | if os.name == 'posix': | |
94 | mapper = lambda s:s |
|
94 | mapper = lambda s:s | |
95 | else: |
|
95 | else: | |
96 | def mapper(s): return s.lower() |
|
96 | def mapper(s): return s.lower() | |
97 |
|
97 | |||
98 | for cmd in syscmds: |
|
98 | for cmd in syscmds: | |
99 | # print "sys",cmd #dbg |
|
99 | # print "sys",cmd #dbg | |
100 | noext, ext = os.path.splitext(cmd) |
|
100 | noext, ext = os.path.splitext(cmd) | |
101 | key = mapper(noext) |
|
101 | key = mapper(noext) | |
102 | if key not in ip.IP.alias_table: |
|
102 | if key not in ip.IP.alias_table: | |
103 | ip.defalias(key, cmd) |
|
103 | ip.defalias(key.replace('.',''), cmd) | |
104 |
|
104 | |||
105 | # mglob combines 'find', recursion, exclusion... '%mglob?' to learn more |
|
105 | # mglob combines 'find', recursion, exclusion... '%mglob?' to learn more | |
106 | ip.load("IPython.external.mglob") |
|
106 | ip.load("IPython.external.mglob") | |
107 |
|
107 | |||
108 | # win32 is crippled w/o cygwin, try to help it a little bit |
|
108 | # win32 is crippled w/o cygwin, try to help it a little bit | |
109 | if sys.platform == 'win32': |
|
109 | if sys.platform == 'win32': | |
110 | if 'cygwin' in os.environ['PATH'].lower(): |
|
110 | if 'cygwin' in os.environ['PATH'].lower(): | |
111 | # use the colors of cygwin ls (recommended) |
|
111 | # use the colors of cygwin ls (recommended) | |
112 | ip.defalias('d', 'ls -F --color=auto') |
|
112 | ip.defalias('d', 'ls -F --color=auto') | |
113 | else: |
|
113 | else: | |
114 | # get icp, imv, imkdir, igrep, irm,... |
|
114 | # get icp, imv, imkdir, igrep, irm,... | |
115 | ip.load('ipy_fsops') |
|
115 | ip.load('ipy_fsops') | |
116 |
|
116 | |||
117 | # and the next best thing to real 'ls -F' |
|
117 | # and the next best thing to real 'ls -F' | |
118 | ip.defalias('d','dir /w /og /on') |
|
118 | ip.defalias('d','dir /w /og /on') | |
119 |
|
119 | |||
120 | ip.set_hook('input_prefilter', dotslash_prefilter_f) |
|
120 | ip.set_hook('input_prefilter', dotslash_prefilter_f) | |
121 | extend_shell_behavior(ip) |
|
121 | extend_shell_behavior(ip) | |
122 |
|
122 | |||
123 | class LastArgFinder: |
|
123 | class LastArgFinder: | |
124 | """ Allow $LA to work as "last argument of previous command", like $! in bash |
|
124 | """ Allow $LA to work as "last argument of previous command", like $! in bash | |
125 |
|
125 | |||
126 | To call this in normal IPython code, do LA() |
|
126 | To call this in normal IPython code, do LA() | |
127 | """ |
|
127 | """ | |
128 | def __call__(self, hist_idx = None): |
|
128 | def __call__(self, hist_idx = None): | |
129 | ip = ipapi.get() |
|
129 | ip = ipapi.get() | |
130 | if hist_idx is None: |
|
130 | if hist_idx is None: | |
131 | return str(self) |
|
131 | return str(self) | |
132 | return ip.IP.input_hist_raw[hist_idx].strip().split()[-1] |
|
132 | return ip.IP.input_hist_raw[hist_idx].strip().split()[-1] | |
133 | def __str__(self): |
|
133 | def __str__(self): | |
134 | ip = ipapi.get() |
|
134 | ip = ipapi.get() | |
135 | for cmd in reversed(ip.IP.input_hist_raw): |
|
135 | for cmd in reversed(ip.IP.input_hist_raw): | |
136 | parts = cmd.strip().split() |
|
136 | parts = cmd.strip().split() | |
137 | if len(parts) < 2 or parts[-1] in ['$LA', 'LA()']: |
|
137 | if len(parts) < 2 or parts[-1] in ['$LA', 'LA()']: | |
138 | continue |
|
138 | continue | |
139 | return parts[-1] |
|
139 | return parts[-1] | |
140 | return "" |
|
140 | return "" | |
141 |
|
141 | |||
142 | def dotslash_prefilter_f(self,line): |
|
142 | def dotslash_prefilter_f(self,line): | |
143 | """ ./foo now runs foo as system command |
|
143 | """ ./foo now runs foo as system command | |
144 |
|
144 | |||
145 | Removes the need for doing !./foo |
|
145 | Removes the need for doing !./foo | |
146 | """ |
|
146 | """ | |
147 | import IPython.genutils |
|
147 | import IPython.genutils | |
148 | if line.startswith("./"): |
|
148 | if line.startswith("./"): | |
149 | return "_ip.system(" + IPython.genutils.make_quoted_expr(line)+")" |
|
149 | return "_ip.system(" + IPython.genutils.make_quoted_expr(line)+")" | |
150 | raise ipapi.TryNext |
|
150 | raise ipapi.TryNext | |
151 |
|
151 | |||
152 | # XXX You do not need to understand the next function! |
|
152 | # XXX You do not need to understand the next function! | |
153 | # This should probably be moved out of profile |
|
153 | # This should probably be moved out of profile | |
154 |
|
154 | |||
155 | def extend_shell_behavior(ip): |
|
155 | def extend_shell_behavior(ip): | |
156 |
|
156 | |||
157 | # Instead of making signature a global variable tie it to IPSHELL. |
|
157 | # Instead of making signature a global variable tie it to IPSHELL. | |
158 | # In future if it is required to distinguish between different |
|
158 | # In future if it is required to distinguish between different | |
159 | # shells we can assign a signature per shell basis |
|
159 | # shells we can assign a signature per shell basis | |
160 | ip.IP.__sig__ = 0xa005 |
|
160 | ip.IP.__sig__ = 0xa005 | |
161 | # mark the IPSHELL with this signature |
|
161 | # mark the IPSHELL with this signature | |
162 | ip.IP.user_ns['__builtins__'].__dict__['__sig__'] = ip.IP.__sig__ |
|
162 | ip.IP.user_ns['__builtins__'].__dict__['__sig__'] = ip.IP.__sig__ | |
163 |
|
163 | |||
164 | from IPython.Itpl import ItplNS |
|
164 | from IPython.Itpl import ItplNS | |
165 | from IPython.genutils import shell |
|
165 | from IPython.genutils import shell | |
166 | # utility to expand user variables via Itpl |
|
166 | # utility to expand user variables via Itpl | |
167 | # xxx do something sensible with depth? |
|
167 | # xxx do something sensible with depth? | |
168 | ip.IP.var_expand = lambda cmd, lvars=None, depth=2: \ |
|
168 | ip.IP.var_expand = lambda cmd, lvars=None, depth=2: \ | |
169 | str(ItplNS(cmd, ip.IP.user_ns, get_locals())) |
|
169 | str(ItplNS(cmd, ip.IP.user_ns, get_locals())) | |
170 |
|
170 | |||
171 | def get_locals(): |
|
171 | def get_locals(): | |
172 | """ Substituting a variable through Itpl deep inside the IPSHELL stack |
|
172 | """ Substituting a variable through Itpl deep inside the IPSHELL stack | |
173 | requires the knowledge of all the variables in scope upto the last |
|
173 | requires the knowledge of all the variables in scope upto the last | |
174 | IPSHELL frame. This routine simply merges all the local variables |
|
174 | IPSHELL frame. This routine simply merges all the local variables | |
175 | on the IPSHELL stack without worrying about their scope rules |
|
175 | on the IPSHELL stack without worrying about their scope rules | |
176 | """ |
|
176 | """ | |
177 | import sys |
|
177 | import sys | |
178 | # note lambda expression constitues a function call |
|
178 | # note lambda expression constitues a function call | |
179 | # hence fno should be incremented by one |
|
179 | # hence fno should be incremented by one | |
180 | getsig = lambda fno: sys._getframe(fno+1).f_globals \ |
|
180 | getsig = lambda fno: sys._getframe(fno+1).f_globals \ | |
181 | ['__builtins__'].__dict__['__sig__'] |
|
181 | ['__builtins__'].__dict__['__sig__'] | |
182 | getlvars = lambda fno: sys._getframe(fno+1).f_locals |
|
182 | getlvars = lambda fno: sys._getframe(fno+1).f_locals | |
183 | # trackback until we enter the IPSHELL |
|
183 | # trackback until we enter the IPSHELL | |
184 | frame_no = 1 |
|
184 | frame_no = 1 | |
185 | sig = ip.IP.__sig__ |
|
185 | sig = ip.IP.__sig__ | |
186 | fsig = ~sig |
|
186 | fsig = ~sig | |
187 | while fsig != sig : |
|
187 | while fsig != sig : | |
188 | try: |
|
188 | try: | |
189 | fsig = getsig(frame_no) |
|
189 | fsig = getsig(frame_no) | |
190 | except (AttributeError, KeyError): |
|
190 | except (AttributeError, KeyError): | |
191 | frame_no += 1 |
|
191 | frame_no += 1 | |
192 | except ValueError: |
|
192 | except ValueError: | |
193 | # stack is depleted |
|
193 | # stack is depleted | |
194 | # call did not originate from IPSHELL |
|
194 | # call did not originate from IPSHELL | |
195 | return {} |
|
195 | return {} | |
196 | first_frame = frame_no |
|
196 | first_frame = frame_no | |
197 | # walk further back until we exit from IPSHELL or deplete stack |
|
197 | # walk further back until we exit from IPSHELL or deplete stack | |
198 | try: |
|
198 | try: | |
199 | while(sig == getsig(frame_no+1)): |
|
199 | while(sig == getsig(frame_no+1)): | |
200 | frame_no += 1 |
|
200 | frame_no += 1 | |
201 | except (AttributeError, KeyError, ValueError): |
|
201 | except (AttributeError, KeyError, ValueError): | |
202 | pass |
|
202 | pass | |
203 | # merge the locals from top down hence overriding |
|
203 | # merge the locals from top down hence overriding | |
204 | # any re-definitions of variables, functions etc. |
|
204 | # any re-definitions of variables, functions etc. | |
205 | lvars = {} |
|
205 | lvars = {} | |
206 | for fno in range(frame_no, first_frame-1, -1): |
|
206 | for fno in range(frame_no, first_frame-1, -1): | |
207 | lvars.update(getlvars(fno)) |
|
207 | lvars.update(getlvars(fno)) | |
208 | #print '\n'*5, first_frame, frame_no, '\n', lvars, '\n'*5 #dbg |
|
208 | #print '\n'*5, first_frame, frame_no, '\n', lvars, '\n'*5 #dbg | |
209 | return lvars |
|
209 | return lvars | |
210 |
|
210 | |||
211 | def _runlines(lines): |
|
211 | def _runlines(lines): | |
212 | """Run a string of one or more lines of source. |
|
212 | """Run a string of one or more lines of source. | |
213 |
|
213 | |||
214 | This method is capable of running a string containing multiple source |
|
214 | This method is capable of running a string containing multiple source | |
215 | lines, as if they had been entered at the IPython prompt. Since it |
|
215 | lines, as if they had been entered at the IPython prompt. Since it | |
216 | exposes IPython's processing machinery, the given strings can contain |
|
216 | exposes IPython's processing machinery, the given strings can contain | |
217 | magic calls (%magic), special shell access (!cmd), etc.""" |
|
217 | magic calls (%magic), special shell access (!cmd), etc.""" | |
218 |
|
218 | |||
219 | # We must start with a clean buffer, in case this is run from an |
|
219 | # We must start with a clean buffer, in case this is run from an | |
220 | # interactive IPython session (via a magic, for example). |
|
220 | # interactive IPython session (via a magic, for example). | |
221 | ip.IP.resetbuffer() |
|
221 | ip.IP.resetbuffer() | |
222 | lines = lines.split('\n') |
|
222 | lines = lines.split('\n') | |
223 | more = 0 |
|
223 | more = 0 | |
224 | command = '' |
|
224 | command = '' | |
225 | for line in lines: |
|
225 | for line in lines: | |
226 | # skip blank lines so we don't mess up the prompt counter, but do |
|
226 | # skip blank lines so we don't mess up the prompt counter, but do | |
227 | # NOT skip even a blank line if we are in a code block (more is |
|
227 | # NOT skip even a blank line if we are in a code block (more is | |
228 | # true) |
|
228 | # true) | |
229 | # if command is not empty trim the line |
|
229 | # if command is not empty trim the line | |
230 | if command != '' : |
|
230 | if command != '' : | |
231 | line = line.strip() |
|
231 | line = line.strip() | |
232 | # add the broken line to the command |
|
232 | # add the broken line to the command | |
233 | if line and line[-1] == '\\' : |
|
233 | if line and line[-1] == '\\' : | |
234 | command += line[0:-1] + ' ' |
|
234 | command += line[0:-1] + ' ' | |
235 | more = True |
|
235 | more = True | |
236 | continue |
|
236 | continue | |
237 | else : |
|
237 | else : | |
238 | # add the last (current) line to the command |
|
238 | # add the last (current) line to the command | |
239 | command += line |
|
239 | command += line | |
240 | if command or more: |
|
240 | if command or more: | |
241 | # push to raw history, so hist line numbers stay in sync |
|
241 | # push to raw history, so hist line numbers stay in sync | |
242 | ip.IP.input_hist_raw.append("# " + command + "\n") |
|
242 | ip.IP.input_hist_raw.append("# " + command + "\n") | |
243 |
|
243 | |||
244 | more = ip.IP.push(ip.IP.prefilter(command,more)) |
|
244 | more = ip.IP.push(ip.IP.prefilter(command,more)) | |
245 | command = '' |
|
245 | command = '' | |
246 | # IPython's runsource returns None if there was an error |
|
246 | # IPython's runsource returns None if there was an error | |
247 | # compiling the code. This allows us to stop processing right |
|
247 | # compiling the code. This allows us to stop processing right | |
248 | # away, so the user gets the error message at the right place. |
|
248 | # away, so the user gets the error message at the right place. | |
249 | if more is None: |
|
249 | if more is None: | |
250 | break |
|
250 | break | |
251 | # final newline in case the input didn't have it, so that the code |
|
251 | # final newline in case the input didn't have it, so that the code | |
252 | # actually does get executed |
|
252 | # actually does get executed | |
253 | if more: |
|
253 | if more: | |
254 | ip.IP.push('\n') |
|
254 | ip.IP.push('\n') | |
255 |
|
255 | |||
256 | ip.IP.runlines = _runlines |
|
256 | ip.IP.runlines = _runlines | |
257 |
|
257 | |||
258 | main() |
|
258 | main() |
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