##// END OF EJS Templates
clean up sh profile banner
vivainio -
Show More
@@ -1,197 +1,202 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 import ipy_which
35 import ipy_stock_completers
35 import ipy_stock_completers
36 import ipy_rehashdir
36 import ipy_rehashdir
37
37
38
38
39 ip.ex('import os')
39 ip.ex('import os')
40 ip.ex("def up(): os.chdir('..')")
40 ip.ex("def up(): os.chdir('..')")
41
41
42 # Nice prompt
42 # Nice prompt
43
43
44 o.prompt_in1= r'\C_LightBlue[\C_LightCyan\Y2\C_LightBlue]\C_Green|\#> '
44 o.prompt_in1= r'\C_LightBlue[\C_LightCyan\Y2\C_LightBlue]\C_Green|\#> '
45 o.prompt_in2= r'\C_Green|\C_LightGreen\D\C_Green> '
45 o.prompt_in2= r'\C_Green|\C_LightGreen\D\C_Green> '
46 o.prompt_out= '<\#> '
46 o.prompt_out= '<\#> '
47
47
48 from IPython import Release
48 from IPython import Release
49
49
50 import sys
50 import sys
51 # I like my banner minimal.
51 # I like my banner minimal.
52 o.banner = "Py %s IPy %s\n" % (sys.version.split('\n')[0],Release.version)
52 o.banner = "IPython %s [on Py %s]\n" % (Release.version,sys.version.split(None,1)[0])
53
53
54 # make 'd' an alias for ls -F
54 # make 'd' an alias for ls -F
55
55
56 ip.magic('alias d ls -F --color=auto')
56 ip.magic('alias d ls -F --color=auto')
57
57
58 ip.IP.default_option('cd','-q')
58 ip.IP.default_option('cd','-q')
59
59
60 # If you only rarely want to execute the things you %edit...
60 # If you only rarely want to execute the things you %edit...
61
61
62 #ip.IP.default_option('edit','-x')
62 #ip.IP.default_option('edit','-x')
63
63
64
64
65 o.prompts_pad_left="1"
65 o.prompts_pad_left="1"
66 # Remove all blank lines in between prompts, like a normal shell.
66 # Remove all blank lines in between prompts, like a normal shell.
67 o.separate_in="0"
67 o.separate_in="0"
68 o.separate_out="0"
68 o.separate_out="0"
69 o.separate_out2="0"
69 o.separate_out2="0"
70
70
71 # now alias all syscommands
71 # now alias all syscommands
72
72
73 db = ip.db
73 db = ip.db
74
74
75 syscmds = db.get("syscmdlist",[] )
75 syscmds = db.get("syscmdlist",[] )
76 if not syscmds:
76 if not syscmds:
77 print textwrap.dedent("""
77 print textwrap.dedent("""
78 System command list not initialized, probably the first run...
78 System command list not initialized, probably the first run...
79 running %rehashx to refresh the command list. Run %rehashx
79 running %rehashx to refresh the command list. Run %rehashx
80 again to refresh command list (after installing new software etc.)
80 again to refresh command list (after installing new software etc.)
81 """)
81 """)
82 ip.magic('rehashx')
82 ip.magic('rehashx')
83 syscmds = db.get("syscmdlist")
83 syscmds = db.get("syscmdlist")
84
84
85 # locase aliases on win#2 only
85 # locase aliases on win#2 only
86 if os.name == 'posix':
86 if os.name == 'posix':
87 mapper = lambda s:s
87 mapper = lambda s:s
88 else:
88 else:
89 def mapper(s): return s.lower()
89 def mapper(s): return s.lower()
90
90
91 for cmd in syscmds:
91 for cmd in syscmds:
92 #print "al",cmd
92 #print "al",cmd
93 noext, ext = os.path.splitext(cmd)
93 noext, ext = os.path.splitext(cmd)
94 ip.IP.alias_table[mapper(noext)] = (0,cmd)
94 ip.IP.alias_table[mapper(noext)] = (0,cmd)
95
96
95 extend_shell_behavior(ip)
97 extend_shell_behavior(ip)
96
98
99 # XXX You do not need to understand the next function!
100 # This should probably be moved out of profile
101
97 def extend_shell_behavior(ip):
102 def extend_shell_behavior(ip):
98
103
99 # Instead of making signature a global variable tie it to IPSHELL.
104 # Instead of making signature a global variable tie it to IPSHELL.
100 # In future if it is required to distinguish between different
105 # In future if it is required to distinguish between different
101 # shells we can assign a signature per shell basis
106 # shells we can assign a signature per shell basis
102 ip.IP.__sig__ = 0xa005
107 ip.IP.__sig__ = 0xa005
103 # mark the IPSHELL with this signature
108 # mark the IPSHELL with this signature
104 ip.IP.user_ns['__builtins__'].__dict__['__sig__'] = ip.IP.__sig__
109 ip.IP.user_ns['__builtins__'].__dict__['__sig__'] = ip.IP.__sig__
105
110
106 from IPython.Itpl import ItplNS
111 from IPython.Itpl import ItplNS
107 from IPython.genutils import shell
112 from IPython.genutils import shell
108 # utility to expand user variables via Itpl
113 # utility to expand user variables via Itpl
109 # xxx do something sensible with depth?
114 # xxx do something sensible with depth?
110 ip.IP.var_expand = lambda cmd, lvars=None, depth=2: \
115 ip.IP.var_expand = lambda cmd, lvars=None, depth=2: \
111 str(ItplNS(cmd.replace('#','\#'), ip.IP.user_ns, get_locals()))
116 str(ItplNS(cmd.replace('#','\#'), ip.IP.user_ns, get_locals()))
112
117
113 def get_locals():
118 def get_locals():
114 """ Substituting a variable through Itpl deep inside the IPSHELL stack
119 """ Substituting a variable through Itpl deep inside the IPSHELL stack
115 requires the knowledge of all the variables in scope upto the last
120 requires the knowledge of all the variables in scope upto the last
116 IPSHELL frame. This routine simply merges all the local variables
121 IPSHELL frame. This routine simply merges all the local variables
117 on the IPSHELL stack without worrying about their scope rules
122 on the IPSHELL stack without worrying about their scope rules
118 """
123 """
119 import sys
124 import sys
120 # note lambda expression constitues a function call
125 # note lambda expression constitues a function call
121 # hence fno should be incremented by one
126 # hence fno should be incremented by one
122 getsig = lambda fno: sys._getframe(fno+1).f_globals \
127 getsig = lambda fno: sys._getframe(fno+1).f_globals \
123 ['__builtins__'].__dict__['__sig__']
128 ['__builtins__'].__dict__['__sig__']
124 getlvars = lambda fno: sys._getframe(fno+1).f_locals
129 getlvars = lambda fno: sys._getframe(fno+1).f_locals
125 # trackback until we enter the IPSHELL
130 # trackback until we enter the IPSHELL
126 frame_no = 1
131 frame_no = 1
127 sig = ip.IP.__sig__
132 sig = ip.IP.__sig__
128 fsig = ~sig
133 fsig = ~sig
129 while fsig != sig :
134 while fsig != sig :
130 try:
135 try:
131 fsig = getsig(frame_no)
136 fsig = getsig(frame_no)
132 except (AttributeError, KeyError):
137 except (AttributeError, KeyError):
133 frame_no += 1
138 frame_no += 1
134 except ValueError:
139 except ValueError:
135 # stack is depleted
140 # stack is depleted
136 # call did not originate from IPSHELL
141 # call did not originate from IPSHELL
137 return {}
142 return {}
138 first_frame = frame_no
143 first_frame = frame_no
139 # walk further back until we exit from IPSHELL or deplete stack
144 # walk further back until we exit from IPSHELL or deplete stack
140 try:
145 try:
141 while(sig == getsig(frame_no+1)):
146 while(sig == getsig(frame_no+1)):
142 frame_no += 1
147 frame_no += 1
143 except (AttributeError, KeyError, ValueError):
148 except (AttributeError, KeyError, ValueError):
144 pass
149 pass
145 # merge the locals from top down hence overriding
150 # merge the locals from top down hence overriding
146 # any re-definitions of variables, functions etc.
151 # any re-definitions of variables, functions etc.
147 lvars = {}
152 lvars = {}
148 for fno in range(frame_no, first_frame-1, -1):
153 for fno in range(frame_no, first_frame-1, -1):
149 lvars.update(getlvars(fno))
154 lvars.update(getlvars(fno))
150 #print '\n'*5, first_frame, frame_no, '\n', lvars, '\n'*5 #dbg
155 #print '\n'*5, first_frame, frame_no, '\n', lvars, '\n'*5 #dbg
151 return lvars
156 return lvars
152
157
153 def _runlines(lines):
158 def _runlines(lines):
154 """Run a string of one or more lines of source.
159 """Run a string of one or more lines of source.
155
160
156 This method is capable of running a string containing multiple source
161 This method is capable of running a string containing multiple source
157 lines, as if they had been entered at the IPython prompt. Since it
162 lines, as if they had been entered at the IPython prompt. Since it
158 exposes IPython's processing machinery, the given strings can contain
163 exposes IPython's processing machinery, the given strings can contain
159 magic calls (%magic), special shell access (!cmd), etc."""
164 magic calls (%magic), special shell access (!cmd), etc."""
160
165
161 # We must start with a clean buffer, in case this is run from an
166 # We must start with a clean buffer, in case this is run from an
162 # interactive IPython session (via a magic, for example).
167 # interactive IPython session (via a magic, for example).
163 ip.IP.resetbuffer()
168 ip.IP.resetbuffer()
164 lines = lines.split('\n')
169 lines = lines.split('\n')
165 more = 0
170 more = 0
166 command = ''
171 command = ''
167 for line in lines:
172 for line in lines:
168 # skip blank lines so we don't mess up the prompt counter, but do
173 # skip blank lines so we don't mess up the prompt counter, but do
169 # NOT skip even a blank line if we are in a code block (more is
174 # NOT skip even a blank line if we are in a code block (more is
170 # true)
175 # true)
171 # if command is not empty trim the line
176 # if command is not empty trim the line
172 if command != '' :
177 if command != '' :
173 line = line.strip()
178 line = line.strip()
174 # add the broken line to the command
179 # add the broken line to the command
175 if line and line[-1] == '\\' :
180 if line and line[-1] == '\\' :
176 command += line[0:-1] + ' '
181 command += line[0:-1] + ' '
177 more = True
182 more = True
178 continue
183 continue
179 else :
184 else :
180 # add the last (current) line to the command
185 # add the last (current) line to the command
181 command += line
186 command += line
182 if command or more:
187 if command or more:
183 more = ip.IP.push(ip.IP.prefilter(command,more))
188 more = ip.IP.push(ip.IP.prefilter(command,more))
184 command = ''
189 command = ''
185 # IPython's runsource returns None if there was an error
190 # IPython's runsource returns None if there was an error
186 # compiling the code. This allows us to stop processing right
191 # compiling the code. This allows us to stop processing right
187 # away, so the user gets the error message at the right place.
192 # away, so the user gets the error message at the right place.
188 if more is None:
193 if more is None:
189 break
194 break
190 # final newline in case the input didn't have it, so that the code
195 # final newline in case the input didn't have it, so that the code
191 # actually does get executed
196 # actually does get executed
192 if more:
197 if more:
193 ip.IP.push('\n')
198 ip.IP.push('\n')
194
199
195 ip.IP.runlines = _runlines
200 ip.IP.runlines = _runlines
196
201
197 main()
202 main()
General Comments 0
You need to be logged in to leave comments. Login now