##// END OF EJS Templates
syscmd aliases - remove dots, so python3.0 => python 30
Ville M. Vainio -
Show More

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

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