##// END OF EJS Templates
Fix pysh profile
fperez -
Show More
@@ -1,270 +1,259 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Modified input prompt for executing files.
2 """Modified input prompt for executing files.
3
3
4 We define a special input line filter to allow typing lines which begin with
4 We define a special input line filter to allow typing lines which begin with
5 '~', '/' or '.'. If one of those strings is encountered, it is automatically
5 '~', '/' or '.'. If one of those strings is encountered, it is automatically
6 executed.
6 executed.
7
7
8 $Id: InterpreterExec.py 1121 2006-02-01 21:12:20Z vivainio $"""
8 $Id: InterpreterExec.py 2724 2007-09-07 08:05:38Z fperez $"""
9
9
10 #*****************************************************************************
10 #*****************************************************************************
11 # Copyright (C) 2004 W.J. van der Laan <gnufnork@hetdigitalegat.nl>
11 # Copyright (C) 2004 W.J. van der Laan <gnufnork@hetdigitalegat.nl>
12 # Copyright (C) 2004-2006 Fernando Perez <fperez@colorado.edu>
12 # Copyright (C) 2004-2006 Fernando Perez <fperez@colorado.edu>
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 from IPython import Release
18 from IPython import Release
19 __author__ = 'W.J. van der Laan <gnufnork@hetdigitalegat.nl>, '\
19 __author__ = 'W.J. van der Laan <gnufnork@hetdigitalegat.nl>, '\
20 '%s <%s>' % Release.authors['Fernando']
20 '%s <%s>' % Release.authors['Fernando']
21 __license__ = Release.license
21 __license__ = Release.license
22
22
23 # TODO: deprecated
23 # TODO: deprecated
24 def prefilter_shell(self,line,continuation):
24 def prefilter_shell(self,line,continuation):
25 """Alternate prefilter, modified for shell-like functionality.
25 """Alternate prefilter, modified for shell-like functionality.
26
26
27 - Execute all lines beginning with '~', '/' or '.'
27 - Execute all lines beginning with '~', '/' or '.'
28 - $var=cmd <=> %sc var=cmd
28 - $var=cmd <=> %sc var=cmd
29 - $$var=cmd <=> %sc -l var=cmd
29 - $$var=cmd <=> %sc -l var=cmd
30 """
30 """
31
31
32 if line:
32 if line:
33 l0 = line[0]
33 l0 = line[0]
34 if l0 in '~/.':
34 if l0 in '~/.':
35 return self._prefilter("!%s"%line,continuation)
35 return self._prefilter("!%s"%line,continuation)
36 elif l0=='$':
36 elif l0=='$':
37 lrest = line[1:]
37 lrest = line[1:]
38 if lrest.startswith('$'):
38 if lrest.startswith('$'):
39 # $$var=cmd <=> %sc -l var=cmd
39 # $$var=cmd <=> %sc -l var=cmd
40 return self._prefilter("%ssc -l %s" % (self.ESC_MAGIC,lrest[1:]),
40 return self._prefilter("%ssc -l %s" % (self.ESC_MAGIC,lrest[1:]),
41 continuation)
41 continuation)
42 else:
42 else:
43 # $var=cmd <=> %sc var=cmd
43 # $var=cmd <=> %sc var=cmd
44 return self._prefilter("%ssc %s" % (self.ESC_MAGIC,lrest),
44 return self._prefilter("%ssc %s" % (self.ESC_MAGIC,lrest),
45 continuation)
45 continuation)
46 else:
46 else:
47 return self._prefilter(line,continuation)
47 return self._prefilter(line,continuation)
48 else:
48 else:
49 return self._prefilter(line,continuation)
49 return self._prefilter(line,continuation)
50
50
51 # Rebind this to be the new IPython prefilter:
51 # Rebind this to be the new IPython prefilter:
52 from IPython.iplib import InteractiveShell
52 from IPython.iplib import InteractiveShell
53 InteractiveShell.prefilter = prefilter_shell
53 InteractiveShell.prefilter = prefilter_shell
54 # Clean up the namespace.
54 # Clean up the namespace.
55 del InteractiveShell,prefilter_shell
55 del InteractiveShell,prefilter_shell
56
56
57 # Provide pysh and further shell-oriented services
57 # Provide pysh and further shell-oriented services
58 import os,sys,shutil
58 import os,sys,shutil
59 from IPython.genutils import system,shell,getoutput,getoutputerror
59 from IPython.genutils import system,shell,getoutput,getoutputerror
60
60
61 # Short aliases for getting shell output as a string and a list
61 # Short aliases for getting shell output as a string and a list
62 sout = getoutput
62 sout = getoutput
63 lout = lambda cmd: getoutput(cmd,split=1)
63 lout = lambda cmd: getoutput(cmd,split=1)
64
64
65 # Empty function, meant as a docstring holder so help(pysh) works.
65 # Empty function, meant as a docstring holder so help(pysh) works.
66 def pysh():
66 def pysh():
67 """Pysh is a set of modules and extensions to IPython which make shell-like
67 """Pysh is a set of modules and extensions to IPython which make shell-like
68 usage with Python syntax more convenient. Keep in mind that pysh is NOT a
68 usage with Python syntax more convenient. Keep in mind that pysh is NOT a
69 full-blown shell, so don't try to make it your /etc/passwd entry!
69 full-blown shell, so don't try to make it your /etc/passwd entry!
70
70
71 In particular, it has no job control, so if you type Ctrl-Z (under Unix),
71 In particular, it has no job control, so if you type Ctrl-Z (under Unix),
72 you'll suspend pysh itself, not the process you just started.
72 you'll suspend pysh itself, not the process you just started.
73
73
74 Since pysh is really nothing but a customized IPython, you should
74 Since pysh is really nothing but a customized IPython, you should
75 familiarize yourself with IPython's features. This brief help mainly
75 familiarize yourself with IPython's features. This brief help mainly
76 documents areas in which pysh differs from the normal IPython.
76 documents areas in which pysh differs from the normal IPython.
77
77
78 ALIASES
78 ALIASES
79 -------
79 -------
80 All of your $PATH has been loaded as IPython aliases, so you should be
80 All of your $PATH has been loaded as IPython aliases, so you should be
81 able to type any normal system command and have it executed. See %alias?
81 able to type any normal system command and have it executed. See %alias?
82 and %unalias? for details on the alias facilities.
82 and %unalias? for details on the alias facilities.
83
83
84 SPECIAL SYNTAX
84 SPECIAL SYNTAX
85 --------------
85 --------------
86 Any lines which begin with '~', '/' and '.' will be executed as shell
86 Any lines which begin with '~', '/' and '.' will be executed as shell
87 commands instead of as Python code. The special escapes below are also
87 commands instead of as Python code. The special escapes below are also
88 recognized. !cmd is valid in single or multi-line input, all others are
88 recognized. !cmd is valid in single or multi-line input, all others are
89 only valid in single-line input:
89 only valid in single-line input:
90
90
91 !cmd - pass 'cmd' directly to the shell
91 !cmd - pass 'cmd' directly to the shell
92 !!cmd - execute 'cmd' and return output as a list (split on '\\n')
92 !!cmd - execute 'cmd' and return output as a list (split on '\\n')
93 $var=cmd - capture output of cmd into var, as a string
93 $var=cmd - capture output of cmd into var, as a string
94 $$var=cmd - capture output of cmd into var, as a list (split on '\\n')
94 $$var=cmd - capture output of cmd into var, as a list (split on '\\n')
95
95
96 The $/$$ syntaxes make Python variables from system output, which you can
96 The $/$$ syntaxes make Python variables from system output, which you can
97 later use for further scripting. The converse is also possible: when
97 later use for further scripting. The converse is also possible: when
98 executing an alias or calling to the system via !/!!, you can expand any
98 executing an alias or calling to the system via !/!!, you can expand any
99 python variable or expression by prepending it with $. Full details of
99 python variable or expression by prepending it with $. Full details of
100 the allowed syntax can be found in Python's PEP 215.
100 the allowed syntax can be found in Python's PEP 215.
101
101
102 A few brief examples will illustrate these:
102 A few brief examples will illustrate these:
103
103
104 fperez[~/test]|3> !ls *s.py
104 fperez[~/test]|3> !ls *s.py
105 scopes.py strings.py
105 scopes.py strings.py
106
106
107 ls is an internal alias, so there's no need to use !:
107 ls is an internal alias, so there's no need to use !:
108 fperez[~/test]|4> ls *s.py
108 fperez[~/test]|4> ls *s.py
109 scopes.py* strings.py
109 scopes.py* strings.py
110
110
111 !!ls will return the output into a Python variable:
111 !!ls will return the output into a Python variable:
112 fperez[~/test]|5> !!ls *s.py
112 fperez[~/test]|5> !!ls *s.py
113 <5> ['scopes.py', 'strings.py']
113 <5> ['scopes.py', 'strings.py']
114 fperez[~/test]|6> print _5
114 fperez[~/test]|6> print _5
115 ['scopes.py', 'strings.py']
115 ['scopes.py', 'strings.py']
116
116
117 $ and $$ allow direct capture to named variables:
117 $ and $$ allow direct capture to named variables:
118 fperez[~/test]|7> $astr = ls *s.py
118 fperez[~/test]|7> $astr = ls *s.py
119 fperez[~/test]|8> astr
119 fperez[~/test]|8> astr
120 <8> 'scopes.py\\nstrings.py'
120 <8> 'scopes.py\\nstrings.py'
121
121
122 fperez[~/test]|9> $$alist = ls *s.py
122 fperez[~/test]|9> $$alist = ls *s.py
123 fperez[~/test]|10> alist
123 fperez[~/test]|10> alist
124 <10> ['scopes.py', 'strings.py']
124 <10> ['scopes.py', 'strings.py']
125
125
126 alist is now a normal python list you can loop over. Using $ will expand
126 alist is now a normal python list you can loop over. Using $ will expand
127 back the python values when alias calls are made:
127 back the python values when alias calls are made:
128 fperez[~/test]|11> for f in alist:
128 fperez[~/test]|11> for f in alist:
129 |..> print 'file',f,
129 |..> print 'file',f,
130 |..> wc -l $f
130 |..> wc -l $f
131 |..>
131 |..>
132 file scopes.py 13 scopes.py
132 file scopes.py 13 scopes.py
133 file strings.py 4 strings.py
133 file strings.py 4 strings.py
134
134
135 Note that you may need to protect your variables with braces if you want
135 Note that you may need to protect your variables with braces if you want
136 to append strings to their names. To copy all files in alist to .bak
136 to append strings to their names. To copy all files in alist to .bak
137 extensions, you must use:
137 extensions, you must use:
138 fperez[~/test]|12> for f in alist:
138 fperez[~/test]|12> for f in alist:
139 |..> cp $f ${f}.bak
139 |..> cp $f ${f}.bak
140
140
141 If you try using $f.bak, you'll get an AttributeError exception saying
141 If you try using $f.bak, you'll get an AttributeError exception saying
142 that your string object doesn't have a .bak attribute. This is because
142 that your string object doesn't have a .bak attribute. This is because
143 the $ expansion mechanism allows you to expand full Python expressions:
143 the $ expansion mechanism allows you to expand full Python expressions:
144 fperez[~/test]|13> echo "sys.platform is: $sys.platform"
144 fperez[~/test]|13> echo "sys.platform is: $sys.platform"
145 sys.platform is: linux2
145 sys.platform is: linux2
146
146
147 IPython's input history handling is still active, which allows you to
147 IPython's input history handling is still active, which allows you to
148 rerun a single block of multi-line input by simply using exec:
148 rerun a single block of multi-line input by simply using exec:
149 fperez[~/test]|14> $$alist = ls *.eps
149 fperez[~/test]|14> $$alist = ls *.eps
150 fperez[~/test]|15> exec _i11
150 fperez[~/test]|15> exec _i11
151 file image2.eps 921 image2.eps
151 file image2.eps 921 image2.eps
152 file image.eps 921 image.eps
152 file image.eps 921 image.eps
153
153
154 While these are new special-case syntaxes, they are designed to allow very
154 While these are new special-case syntaxes, they are designed to allow very
155 efficient use of the shell with minimal typing. At an interactive shell
155 efficient use of the shell with minimal typing. At an interactive shell
156 prompt, conciseness of expression wins over readability.
156 prompt, conciseness of expression wins over readability.
157
157
158 USEFUL FUNCTIONS AND MODULES
158 USEFUL FUNCTIONS AND MODULES
159 ----------------------------
159 ----------------------------
160 The os, sys and shutil modules from the Python standard library are
160 The os, sys and shutil modules from the Python standard library are
161 automatically loaded. Some additional functions, useful for shell usage,
161 automatically loaded. Some additional functions, useful for shell usage,
162 are listed below. You can request more help about them with '?'.
162 are listed below. You can request more help about them with '?'.
163
163
164 shell - execute a command in the underlying system shell
164 shell - execute a command in the underlying system shell
165 system - like shell(), but return the exit status of the command
165 system - like shell(), but return the exit status of the command
166 sout - capture the output of a command as a string
166 sout - capture the output of a command as a string
167 lout - capture the output of a command as a list (split on '\\n')
167 lout - capture the output of a command as a list (split on '\\n')
168 getoutputerror - capture (output,error) of a shell command
168 getoutputerror - capture (output,error) of a shell command
169
169
170 sout/lout are the functional equivalents of $/$$. They are provided to
170 sout/lout are the functional equivalents of $/$$. They are provided to
171 allow you to capture system output in the middle of true python code,
171 allow you to capture system output in the middle of true python code,
172 function definitions, etc (where $ and $$ are invalid).
172 function definitions, etc (where $ and $$ are invalid).
173
173
174 DIRECTORY MANAGEMENT
174 DIRECTORY MANAGEMENT
175 --------------------
175 --------------------
176 Since each command passed by pysh to the underlying system is executed in
176 Since each command passed by pysh to the underlying system is executed in
177 a subshell which exits immediately, you can NOT use !cd to navigate the
177 a subshell which exits immediately, you can NOT use !cd to navigate the
178 filesystem.
178 filesystem.
179
179
180 Pysh provides its own builtin '%cd' magic command to move in the
180 Pysh provides its own builtin '%cd' magic command to move in the
181 filesystem (the % is not required with automagic on). It also maintains a
181 filesystem (the % is not required with automagic on). It also maintains a
182 list of visited directories (use %dhist to see it) and allows direct
182 list of visited directories (use %dhist to see it) and allows direct
183 switching to any of them. Type 'cd?' for more details.
183 switching to any of them. Type 'cd?' for more details.
184
184
185 %pushd, %popd and %dirs are provided for directory stack handling.
185 %pushd, %popd and %dirs are provided for directory stack handling.
186
186
187 PROMPT CUSTOMIZATION
187 PROMPT CUSTOMIZATION
188 --------------------
188 --------------------
189
189
190 The supplied ipythonrc-pysh profile comes with an example of a very
190 The supplied ipythonrc-pysh profile comes with an example of a very
191 colored and detailed prompt, mainly to serve as an illustration. The
191 colored and detailed prompt, mainly to serve as an illustration. The
192 valid escape sequences, besides color names, are:
192 valid escape sequences, besides color names, are:
193
193
194 \\# - Prompt number.
194 \\# - Prompt number.
195 \\D - Dots, as many as there are digits in \\# (so they align).
195 \\D - Dots, as many as there are digits in \\# (so they align).
196 \\w - Current working directory (cwd).
196 \\w - Current working directory (cwd).
197 \\W - Basename of current working directory.
197 \\W - Basename of current working directory.
198 \\XN - Where N=0..5. N terms of the cwd, with $HOME written as ~.
198 \\XN - Where N=0..5. N terms of the cwd, with $HOME written as ~.
199 \\YN - Where N=0..5. Like XN, but if ~ is term N+1 it's also shown.
199 \\YN - Where N=0..5. Like XN, but if ~ is term N+1 it's also shown.
200 \\u - Username.
200 \\u - Username.
201 \\H - Full hostname.
201 \\H - Full hostname.
202 \\h - Hostname up to first '.'
202 \\h - Hostname up to first '.'
203 \\$ - Root symbol ($ or #).
203 \\$ - Root symbol ($ or #).
204 \\t - Current time, in H:M:S format.
204 \\t - Current time, in H:M:S format.
205 \\v - IPython release version.
205 \\v - IPython release version.
206 \\n - Newline.
206 \\n - Newline.
207 \\r - Carriage return.
207 \\r - Carriage return.
208 \\\\ - An explicitly escaped '\\'.
208 \\\\ - An explicitly escaped '\\'.
209
209
210 You can configure your prompt colors using any ANSI color escape. Each
210 You can configure your prompt colors using any ANSI color escape. Each
211 color escape sets the color for any subsequent text, until another escape
211 color escape sets the color for any subsequent text, until another escape
212 comes in and changes things. The valid color escapes are:
212 comes in and changes things. The valid color escapes are:
213
213
214 \\C_Black
214 \\C_Black
215 \\C_Blue
215 \\C_Blue
216 \\C_Brown
216 \\C_Brown
217 \\C_Cyan
217 \\C_Cyan
218 \\C_DarkGray
218 \\C_DarkGray
219 \\C_Green
219 \\C_Green
220 \\C_LightBlue
220 \\C_LightBlue
221 \\C_LightCyan
221 \\C_LightCyan
222 \\C_LightGray
222 \\C_LightGray
223 \\C_LightGreen
223 \\C_LightGreen
224 \\C_LightPurple
224 \\C_LightPurple
225 \\C_LightRed
225 \\C_LightRed
226 \\C_Purple
226 \\C_Purple
227 \\C_Red
227 \\C_Red
228 \\C_White
228 \\C_White
229 \\C_Yellow
229 \\C_Yellow
230 \\C_Normal - Stop coloring, defaults to your terminal settings.
230 \\C_Normal - Stop coloring, defaults to your terminal settings.
231 """
231 """
232 pass
232 pass
233
233
234 # Configure a few things. Much of this is fairly hackish, since IPython
234 # Configure a few things. Much of this is fairly hackish, since IPython
235 # doesn't really expose a clean API for it. Be careful if you start making
235 # doesn't really expose a clean API for it. Be careful if you start making
236 # many modifications here.
236 # many modifications here.
237
237
238
238
239 # Set the 'cd' command to quiet mode, a more shell-like behavior
239 # Set the 'cd' command to quiet mode, a more shell-like behavior
240 __IPYTHON__.default_option('cd','-q')
240 __IPYTHON__.default_option('cd','-q')
241
241
242 # This is redundant, ipy_user_conf.py will determine this
242 # This is redundant, ipy_user_conf.py will determine this
243 # Load all of $PATH as aliases
243 # Load all of $PATH as aliases
244 if os.name == 'posix':
244 __IPYTHON__.magic_rehashx()
245 # # %rehash is very fast, but it doesn't check for executability, it simply
246 # # dumps everything in $PATH as an alias. Use rehashx if you want more
247 # # checks.
248 __IPYTHON__.magic_rehash()
249 else:
250 # # Windows users: the list of extensions considered executable is read from
251 # # the environment variable 'pathext'. If this is undefined, IPython
252 # # defaults to EXE, COM and BAT.
253 # # %rehashx is the one which does extension analysis, at the cost of
254 # # being much slower than %rehash.
255 __IPYTHON__.magic_rehashx()
256
245
257 # Remove %sc,%sx if present as aliases
246 # Remove %sc,%sx if present as aliases
258 __IPYTHON__.magic_unalias('sc')
247 __IPYTHON__.magic_unalias('sc')
259 __IPYTHON__.magic_unalias('sx')
248 __IPYTHON__.magic_unalias('sx')
260
249
261 # We need different criteria for line-splitting, so that aliases such as
250 # We need different criteria for line-splitting, so that aliases such as
262 # 'gnome-terminal' are interpreted as a single alias instead of variable
251 # 'gnome-terminal' are interpreted as a single alias instead of variable
263 # 'gnome' minus variable 'terminal'.
252 # 'gnome' minus variable 'terminal'.
264 import re
253 import re
265 __IPYTHON__.line_split = re.compile(r'^([\s*,;/])'
254 __IPYTHON__.line_split = re.compile(r'^([\s*,;/])'
266 r'([\?\w\.\-\+]+\w*\s*)'
255 r'([\?\w\.\-\+]+\w*\s*)'
267 r'(\(?.*$)')
256 r'(\(?.*$)')
268
257
269 # Namespace cleanup
258 # Namespace cleanup
270 del re
259 del re
General Comments 0
You need to be logged in to leave comments. Login now