##// END OF EJS Templates
Merge pull request #12343 from btel/patch-1...
Matthias Bussonnier -
r25774:5886f9a3 merge
parent child Browse files
Show More
@@ -1,849 +1,849 b''
1 """Implementation of magic functions for interaction with the OS.
1 """Implementation of magic functions for interaction with the OS.
2
2
3 Note: this module is named 'osm' instead of 'os' to avoid a collision with the
3 Note: this module is named 'osm' instead of 'os' to avoid a collision with the
4 builtin.
4 builtin.
5 """
5 """
6 # Copyright (c) IPython Development Team.
6 # Copyright (c) IPython Development Team.
7 # Distributed under the terms of the Modified BSD License.
7 # Distributed under the terms of the Modified BSD License.
8
8
9 import io
9 import io
10 import os
10 import os
11 import re
11 import re
12 import sys
12 import sys
13 from pprint import pformat
13 from pprint import pformat
14
14
15 from IPython.core import magic_arguments
15 from IPython.core import magic_arguments
16 from IPython.core import oinspect
16 from IPython.core import oinspect
17 from IPython.core import page
17 from IPython.core import page
18 from IPython.core.alias import AliasError, Alias
18 from IPython.core.alias import AliasError, Alias
19 from IPython.core.error import UsageError
19 from IPython.core.error import UsageError
20 from IPython.core.magic import (
20 from IPython.core.magic import (
21 Magics, compress_dhist, magics_class, line_magic, cell_magic, line_cell_magic
21 Magics, compress_dhist, magics_class, line_magic, cell_magic, line_cell_magic
22 )
22 )
23 from IPython.testing.skipdoctest import skip_doctest
23 from IPython.testing.skipdoctest import skip_doctest
24 from IPython.utils.openpy import source_to_unicode
24 from IPython.utils.openpy import source_to_unicode
25 from IPython.utils.process import abbrev_cwd
25 from IPython.utils.process import abbrev_cwd
26 from IPython.utils.terminal import set_term_title
26 from IPython.utils.terminal import set_term_title
27 from traitlets import Bool
27 from traitlets import Bool
28
28
29
29
30 @magics_class
30 @magics_class
31 class OSMagics(Magics):
31 class OSMagics(Magics):
32 """Magics to interact with the underlying OS (shell-type functionality).
32 """Magics to interact with the underlying OS (shell-type functionality).
33 """
33 """
34
34
35 cd_force_quiet = Bool(False,
35 cd_force_quiet = Bool(False,
36 help="Force %cd magic to be quiet even if -q is not passed."
36 help="Force %cd magic to be quiet even if -q is not passed."
37 ).tag(config=True)
37 ).tag(config=True)
38
38
39 def __init__(self, shell=None, **kwargs):
39 def __init__(self, shell=None, **kwargs):
40
40
41 # Now define isexec in a cross platform manner.
41 # Now define isexec in a cross platform manner.
42 self.is_posix = False
42 self.is_posix = False
43 self.execre = None
43 self.execre = None
44 if os.name == 'posix':
44 if os.name == 'posix':
45 self.is_posix = True
45 self.is_posix = True
46 else:
46 else:
47 try:
47 try:
48 winext = os.environ['pathext'].replace(';','|').replace('.','')
48 winext = os.environ['pathext'].replace(';','|').replace('.','')
49 except KeyError:
49 except KeyError:
50 winext = 'exe|com|bat|py'
50 winext = 'exe|com|bat|py'
51
51
52 self.execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
52 self.execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
53
53
54 # call up the chain
54 # call up the chain
55 super().__init__(shell=shell, **kwargs)
55 super().__init__(shell=shell, **kwargs)
56
56
57
57
58 @skip_doctest
58 @skip_doctest
59 def _isexec_POSIX(self, file):
59 def _isexec_POSIX(self, file):
60 """
60 """
61 Test for executable on a POSIX system
61 Test for executable on a POSIX system
62 """
62 """
63 if os.access(file.path, os.X_OK):
63 if os.access(file.path, os.X_OK):
64 # will fail on maxOS if access is not X_OK
64 # will fail on maxOS if access is not X_OK
65 return file.is_file()
65 return file.is_file()
66 return False
66 return False
67
67
68
68
69
69
70 @skip_doctest
70 @skip_doctest
71 def _isexec_WIN(self, file):
71 def _isexec_WIN(self, file):
72 """
72 """
73 Test for executable file on non POSIX system
73 Test for executable file on non POSIX system
74 """
74 """
75 return file.is_file() and self.execre.match(file.name) is not None
75 return file.is_file() and self.execre.match(file.name) is not None
76
76
77 @skip_doctest
77 @skip_doctest
78 def isexec(self, file):
78 def isexec(self, file):
79 """
79 """
80 Test for executable file on non POSIX system
80 Test for executable file on non POSIX system
81 """
81 """
82 if self.is_posix:
82 if self.is_posix:
83 return self._isexec_POSIX(file)
83 return self._isexec_POSIX(file)
84 else:
84 else:
85 return self._isexec_WIN(file)
85 return self._isexec_WIN(file)
86
86
87
87
88 @skip_doctest
88 @skip_doctest
89 @line_magic
89 @line_magic
90 def alias(self, parameter_s=''):
90 def alias(self, parameter_s=''):
91 """Define an alias for a system command.
91 """Define an alias for a system command.
92
92
93 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
93 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
94
94
95 Then, typing 'alias_name params' will execute the system command 'cmd
95 Then, typing 'alias_name params' will execute the system command 'cmd
96 params' (from your underlying operating system).
96 params' (from your underlying operating system).
97
97
98 Aliases have lower precedence than magic functions and Python normal
98 Aliases have lower precedence than magic functions and Python normal
99 variables, so if 'foo' is both a Python variable and an alias, the
99 variables, so if 'foo' is both a Python variable and an alias, the
100 alias can not be executed until 'del foo' removes the Python variable.
100 alias can not be executed until 'del foo' removes the Python variable.
101
101
102 You can use the %l specifier in an alias definition to represent the
102 You can use the %l specifier in an alias definition to represent the
103 whole line when the alias is called. For example::
103 whole line when the alias is called. For example::
104
104
105 In [2]: alias bracket echo "Input in brackets: <%l>"
105 In [2]: alias bracket echo "Input in brackets: <%l>"
106 In [3]: bracket hello world
106 In [3]: bracket hello world
107 Input in brackets: <hello world>
107 Input in brackets: <hello world>
108
108
109 You can also define aliases with parameters using %s specifiers (one
109 You can also define aliases with parameters using %s specifiers (one
110 per parameter)::
110 per parameter)::
111
111
112 In [1]: alias parts echo first %s second %s
112 In [1]: alias parts echo first %s second %s
113 In [2]: %parts A B
113 In [2]: %parts A B
114 first A second B
114 first A second B
115 In [3]: %parts A
115 In [3]: %parts A
116 Incorrect number of arguments: 2 expected.
116 Incorrect number of arguments: 2 expected.
117 parts is an alias to: 'echo first %s second %s'
117 parts is an alias to: 'echo first %s second %s'
118
118
119 Note that %l and %s are mutually exclusive. You can only use one or
119 Note that %l and %s are mutually exclusive. You can only use one or
120 the other in your aliases.
120 the other in your aliases.
121
121
122 Aliases expand Python variables just like system calls using ! or !!
122 Aliases expand Python variables just like system calls using ! or !!
123 do: all expressions prefixed with '$' get expanded. For details of
123 do: all expressions prefixed with '$' get expanded. For details of
124 the semantic rules, see PEP-215:
124 the semantic rules, see PEP-215:
125 http://www.python.org/peps/pep-0215.html. This is the library used by
125 http://www.python.org/peps/pep-0215.html. This is the library used by
126 IPython for variable expansion. If you want to access a true shell
126 IPython for variable expansion. If you want to access a true shell
127 variable, an extra $ is necessary to prevent its expansion by
127 variable, an extra $ is necessary to prevent its expansion by
128 IPython::
128 IPython::
129
129
130 In [6]: alias show echo
130 In [6]: alias show echo
131 In [7]: PATH='A Python string'
131 In [7]: PATH='A Python string'
132 In [8]: show $PATH
132 In [8]: show $PATH
133 A Python string
133 A Python string
134 In [9]: show $$PATH
134 In [9]: show $$PATH
135 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
135 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
136
136
137 You can use the alias facility to access all of $PATH. See the %rehashx
137 You can use the alias facility to access all of $PATH. See the %rehashx
138 function, which automatically creates aliases for the contents of your
138 function, which automatically creates aliases for the contents of your
139 $PATH.
139 $PATH.
140
140
141 If called with no parameters, %alias prints the current alias table
141 If called with no parameters, %alias prints the current alias table
142 for your system. For posix systems, the default aliases are 'cat',
142 for your system. For posix systems, the default aliases are 'cat',
143 'cp', 'mv', 'rm', 'rmdir', and 'mkdir', and other platform-specific
143 'cp', 'mv', 'rm', 'rmdir', and 'mkdir', and other platform-specific
144 aliases are added. For windows-based systems, the default aliases are
144 aliases are added. For windows-based systems, the default aliases are
145 'copy', 'ddir', 'echo', 'ls', 'ldir', 'mkdir', 'ren', and 'rmdir'.
145 'copy', 'ddir', 'echo', 'ls', 'ldir', 'mkdir', 'ren', and 'rmdir'.
146
146
147 You can see the definition of alias by adding a question mark in the
147 You can see the definition of alias by adding a question mark in the
148 end::
148 end::
149
149
150 In [1]: cat?
150 In [1]: cat?
151 Repr: <alias cat for 'cat'>"""
151 Repr: <alias cat for 'cat'>"""
152
152
153 par = parameter_s.strip()
153 par = parameter_s.strip()
154 if not par:
154 if not par:
155 aliases = sorted(self.shell.alias_manager.aliases)
155 aliases = sorted(self.shell.alias_manager.aliases)
156 # stored = self.shell.db.get('stored_aliases', {} )
156 # stored = self.shell.db.get('stored_aliases', {} )
157 # for k, v in stored:
157 # for k, v in stored:
158 # atab.append(k, v[0])
158 # atab.append(k, v[0])
159
159
160 print("Total number of aliases:", len(aliases))
160 print("Total number of aliases:", len(aliases))
161 sys.stdout.flush()
161 sys.stdout.flush()
162 return aliases
162 return aliases
163
163
164 # Now try to define a new one
164 # Now try to define a new one
165 try:
165 try:
166 alias,cmd = par.split(None, 1)
166 alias,cmd = par.split(None, 1)
167 except TypeError:
167 except TypeError:
168 print(oinspect.getdoc(self.alias))
168 print(oinspect.getdoc(self.alias))
169 return
169 return
170
170
171 try:
171 try:
172 self.shell.alias_manager.define_alias(alias, cmd)
172 self.shell.alias_manager.define_alias(alias, cmd)
173 except AliasError as e:
173 except AliasError as e:
174 print(e)
174 print(e)
175 # end magic_alias
175 # end magic_alias
176
176
177 @line_magic
177 @line_magic
178 def unalias(self, parameter_s=''):
178 def unalias(self, parameter_s=''):
179 """Remove an alias"""
179 """Remove an alias"""
180
180
181 aname = parameter_s.strip()
181 aname = parameter_s.strip()
182 try:
182 try:
183 self.shell.alias_manager.undefine_alias(aname)
183 self.shell.alias_manager.undefine_alias(aname)
184 except ValueError as e:
184 except ValueError as e:
185 print(e)
185 print(e)
186 return
186 return
187
187
188 stored = self.shell.db.get('stored_aliases', {} )
188 stored = self.shell.db.get('stored_aliases', {} )
189 if aname in stored:
189 if aname in stored:
190 print("Removing %stored alias",aname)
190 print("Removing %stored alias",aname)
191 del stored[aname]
191 del stored[aname]
192 self.shell.db['stored_aliases'] = stored
192 self.shell.db['stored_aliases'] = stored
193
193
194 @line_magic
194 @line_magic
195 def rehashx(self, parameter_s=''):
195 def rehashx(self, parameter_s=''):
196 """Update the alias table with all executable files in $PATH.
196 """Update the alias table with all executable files in $PATH.
197
197
198 rehashx explicitly checks that every entry in $PATH is a file
198 rehashx explicitly checks that every entry in $PATH is a file
199 with execute access (os.X_OK).
199 with execute access (os.X_OK).
200
200
201 Under Windows, it checks executability as a match against a
201 Under Windows, it checks executability as a match against a
202 '|'-separated string of extensions, stored in the IPython config
202 '|'-separated string of extensions, stored in the IPython config
203 variable win_exec_ext. This defaults to 'exe|com|bat'.
203 variable win_exec_ext. This defaults to 'exe|com|bat'.
204
204
205 This function also resets the root module cache of module completer,
205 This function also resets the root module cache of module completer,
206 used on slow filesystems.
206 used on slow filesystems.
207 """
207 """
208 from IPython.core.alias import InvalidAliasError
208 from IPython.core.alias import InvalidAliasError
209
209
210 # for the benefit of module completer in ipy_completers.py
210 # for the benefit of module completer in ipy_completers.py
211 del self.shell.db['rootmodules_cache']
211 del self.shell.db['rootmodules_cache']
212
212
213 path = [os.path.abspath(os.path.expanduser(p)) for p in
213 path = [os.path.abspath(os.path.expanduser(p)) for p in
214 os.environ.get('PATH','').split(os.pathsep)]
214 os.environ.get('PATH','').split(os.pathsep)]
215
215
216 syscmdlist = []
216 syscmdlist = []
217 savedir = os.getcwd()
217 savedir = os.getcwd()
218
218
219 # Now walk the paths looking for executables to alias.
219 # Now walk the paths looking for executables to alias.
220 try:
220 try:
221 # write the whole loop for posix/Windows so we don't have an if in
221 # write the whole loop for posix/Windows so we don't have an if in
222 # the innermost part
222 # the innermost part
223 if self.is_posix:
223 if self.is_posix:
224 for pdir in path:
224 for pdir in path:
225 try:
225 try:
226 os.chdir(pdir)
226 os.chdir(pdir)
227 except OSError:
227 except OSError:
228 continue
228 continue
229
229
230 # for python 3.6+ rewrite to: with os.scandir(pdir) as dirlist:
230 # for python 3.6+ rewrite to: with os.scandir(pdir) as dirlist:
231 dirlist = os.scandir(path=pdir)
231 dirlist = os.scandir(path=pdir)
232 for ff in dirlist:
232 for ff in dirlist:
233 if self.isexec(ff):
233 if self.isexec(ff):
234 fname = ff.name
234 fname = ff.name
235 try:
235 try:
236 # Removes dots from the name since ipython
236 # Removes dots from the name since ipython
237 # will assume names with dots to be python.
237 # will assume names with dots to be python.
238 if not self.shell.alias_manager.is_alias(fname):
238 if not self.shell.alias_manager.is_alias(fname):
239 self.shell.alias_manager.define_alias(
239 self.shell.alias_manager.define_alias(
240 fname.replace('.',''), fname)
240 fname.replace('.',''), fname)
241 except InvalidAliasError:
241 except InvalidAliasError:
242 pass
242 pass
243 else:
243 else:
244 syscmdlist.append(fname)
244 syscmdlist.append(fname)
245 else:
245 else:
246 no_alias = Alias.blacklist
246 no_alias = Alias.blacklist
247 for pdir in path:
247 for pdir in path:
248 try:
248 try:
249 os.chdir(pdir)
249 os.chdir(pdir)
250 except OSError:
250 except OSError:
251 continue
251 continue
252
252
253 # for python 3.6+ rewrite to: with os.scandir(pdir) as dirlist:
253 # for python 3.6+ rewrite to: with os.scandir(pdir) as dirlist:
254 dirlist = os.scandir(pdir)
254 dirlist = os.scandir(pdir)
255 for ff in dirlist:
255 for ff in dirlist:
256 fname = ff.name
256 fname = ff.name
257 base, ext = os.path.splitext(fname)
257 base, ext = os.path.splitext(fname)
258 if self.isexec(ff) and base.lower() not in no_alias:
258 if self.isexec(ff) and base.lower() not in no_alias:
259 if ext.lower() == '.exe':
259 if ext.lower() == '.exe':
260 fname = base
260 fname = base
261 try:
261 try:
262 # Removes dots from the name since ipython
262 # Removes dots from the name since ipython
263 # will assume names with dots to be python.
263 # will assume names with dots to be python.
264 self.shell.alias_manager.define_alias(
264 self.shell.alias_manager.define_alias(
265 base.lower().replace('.',''), fname)
265 base.lower().replace('.',''), fname)
266 except InvalidAliasError:
266 except InvalidAliasError:
267 pass
267 pass
268 syscmdlist.append(fname)
268 syscmdlist.append(fname)
269
269
270 self.shell.db['syscmdlist'] = syscmdlist
270 self.shell.db['syscmdlist'] = syscmdlist
271 finally:
271 finally:
272 os.chdir(savedir)
272 os.chdir(savedir)
273
273
274 @skip_doctest
274 @skip_doctest
275 @line_magic
275 @line_magic
276 def pwd(self, parameter_s=''):
276 def pwd(self, parameter_s=''):
277 """Return the current working directory path.
277 """Return the current working directory path.
278
278
279 Examples
279 Examples
280 --------
280 --------
281 ::
281 ::
282
282
283 In [9]: pwd
283 In [9]: pwd
284 Out[9]: '/home/tsuser/sprint/ipython'
284 Out[9]: '/home/tsuser/sprint/ipython'
285 """
285 """
286 try:
286 try:
287 return os.getcwd()
287 return os.getcwd()
288 except FileNotFoundError:
288 except FileNotFoundError:
289 raise UsageError("CWD no longer exists - please use %cd to change directory.")
289 raise UsageError("CWD no longer exists - please use %cd to change directory.")
290
290
291 @skip_doctest
291 @skip_doctest
292 @line_magic
292 @line_magic
293 def cd(self, parameter_s=''):
293 def cd(self, parameter_s=''):
294 """Change the current working directory.
294 """Change the current working directory.
295
295
296 This command automatically maintains an internal list of directories
296 This command automatically maintains an internal list of directories
297 you visit during your IPython session, in the variable _dh. The
297 you visit during your IPython session, in the variable _dh. The
298 command %dhist shows this history nicely formatted. You can also
298 command %dhist shows this history nicely formatted. You can also
299 do 'cd -<tab>' to see directory history conveniently.
299 do 'cd -<tab>' to see directory history conveniently.
300
300
301 Usage:
301 Usage:
302
302
303 cd 'dir': changes to directory 'dir'.
303 cd 'dir': changes to directory 'dir'.
304
304
305 cd -: changes to the last visited directory.
305 cd -: changes to the last visited directory.
306
306
307 cd -<n>: changes to the n-th directory in the directory history.
307 cd -<n>: changes to the n-th directory in the directory history.
308
308
309 cd --foo: change to directory that matches 'foo' in history
309 cd --foo: change to directory that matches 'foo' in history
310
310
311 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
311 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
312 (note: cd <bookmark_name> is enough if there is no
312 (note: cd <bookmark_name> is enough if there is no
313 directory <bookmark_name>, but a bookmark with the name exists.)
313 directory <bookmark_name>, but a bookmark with the name exists.)
314 'cd -b <tab>' allows you to tab-complete bookmark names.
314 'cd -b <tab>' allows you to tab-complete bookmark names.
315
315
316 Options:
316 Options:
317
317
318 -q: quiet. Do not print the working directory after the cd command is
318 -q: quiet. Do not print the working directory after the cd command is
319 executed. By default IPython's cd command does print this directory,
319 executed. By default IPython's cd command does print this directory,
320 since the default prompts do not display path information.
320 since the default prompts do not display path information.
321
321
322 Note that !cd doesn't work for this purpose because the shell where
322 Note that !cd doesn't work for this purpose because the shell where
323 !command runs is immediately discarded after executing 'command'.
323 !command runs is immediately discarded after executing 'command'.
324
324
325 Examples
325 Examples
326 --------
326 --------
327 ::
327 ::
328
328
329 In [10]: cd parent/child
329 In [10]: cd parent/child
330 /home/tsuser/parent/child
330 /home/tsuser/parent/child
331 """
331 """
332
332
333 try:
333 try:
334 oldcwd = os.getcwd()
334 oldcwd = os.getcwd()
335 except FileNotFoundError:
335 except FileNotFoundError:
336 # Happens if the CWD has been deleted.
336 # Happens if the CWD has been deleted.
337 oldcwd = None
337 oldcwd = None
338
338
339 numcd = re.match(r'(-)(\d+)$',parameter_s)
339 numcd = re.match(r'(-)(\d+)$',parameter_s)
340 # jump in directory history by number
340 # jump in directory history by number
341 if numcd:
341 if numcd:
342 nn = int(numcd.group(2))
342 nn = int(numcd.group(2))
343 try:
343 try:
344 ps = self.shell.user_ns['_dh'][nn]
344 ps = self.shell.user_ns['_dh'][nn]
345 except IndexError:
345 except IndexError:
346 print('The requested directory does not exist in history.')
346 print('The requested directory does not exist in history.')
347 return
347 return
348 else:
348 else:
349 opts = {}
349 opts = {}
350 elif parameter_s.startswith('--'):
350 elif parameter_s.startswith('--'):
351 ps = None
351 ps = None
352 fallback = None
352 fallback = None
353 pat = parameter_s[2:]
353 pat = parameter_s[2:]
354 dh = self.shell.user_ns['_dh']
354 dh = self.shell.user_ns['_dh']
355 # first search only by basename (last component)
355 # first search only by basename (last component)
356 for ent in reversed(dh):
356 for ent in reversed(dh):
357 if pat in os.path.basename(ent) and os.path.isdir(ent):
357 if pat in os.path.basename(ent) and os.path.isdir(ent):
358 ps = ent
358 ps = ent
359 break
359 break
360
360
361 if fallback is None and pat in ent and os.path.isdir(ent):
361 if fallback is None and pat in ent and os.path.isdir(ent):
362 fallback = ent
362 fallback = ent
363
363
364 # if we have no last part match, pick the first full path match
364 # if we have no last part match, pick the first full path match
365 if ps is None:
365 if ps is None:
366 ps = fallback
366 ps = fallback
367
367
368 if ps is None:
368 if ps is None:
369 print("No matching entry in directory history")
369 print("No matching entry in directory history")
370 return
370 return
371 else:
371 else:
372 opts = {}
372 opts = {}
373
373
374
374
375 else:
375 else:
376 opts, ps = self.parse_options(parameter_s, 'qb', mode='string')
376 opts, ps = self.parse_options(parameter_s, 'qb', mode='string')
377 # jump to previous
377 # jump to previous
378 if ps == '-':
378 if ps == '-':
379 try:
379 try:
380 ps = self.shell.user_ns['_dh'][-2]
380 ps = self.shell.user_ns['_dh'][-2]
381 except IndexError:
381 except IndexError:
382 raise UsageError('%cd -: No previous directory to change to.')
382 raise UsageError('%cd -: No previous directory to change to.')
383 # jump to bookmark if needed
383 # jump to bookmark if needed
384 else:
384 else:
385 if not os.path.isdir(ps) or 'b' in opts:
385 if not os.path.isdir(ps) or 'b' in opts:
386 bkms = self.shell.db.get('bookmarks', {})
386 bkms = self.shell.db.get('bookmarks', {})
387
387
388 if ps in bkms:
388 if ps in bkms:
389 target = bkms[ps]
389 target = bkms[ps]
390 print('(bookmark:%s) -> %s' % (ps, target))
390 print('(bookmark:%s) -> %s' % (ps, target))
391 ps = target
391 ps = target
392 else:
392 else:
393 if 'b' in opts:
393 if 'b' in opts:
394 raise UsageError("Bookmark '%s' not found. "
394 raise UsageError("Bookmark '%s' not found. "
395 "Use '%%bookmark -l' to see your bookmarks." % ps)
395 "Use '%%bookmark -l' to see your bookmarks." % ps)
396
396
397 # at this point ps should point to the target dir
397 # at this point ps should point to the target dir
398 if ps:
398 if ps:
399 try:
399 try:
400 os.chdir(os.path.expanduser(ps))
400 os.chdir(os.path.expanduser(ps))
401 if hasattr(self.shell, 'term_title') and self.shell.term_title:
401 if hasattr(self.shell, 'term_title') and self.shell.term_title:
402 set_term_title(self.shell.term_title_format.format(cwd=abbrev_cwd()))
402 set_term_title(self.shell.term_title_format.format(cwd=abbrev_cwd()))
403 except OSError:
403 except OSError:
404 print(sys.exc_info()[1])
404 print(sys.exc_info()[1])
405 else:
405 else:
406 cwd = os.getcwd()
406 cwd = os.getcwd()
407 dhist = self.shell.user_ns['_dh']
407 dhist = self.shell.user_ns['_dh']
408 if oldcwd != cwd:
408 if oldcwd != cwd:
409 dhist.append(cwd)
409 dhist.append(cwd)
410 self.shell.db['dhist'] = compress_dhist(dhist)[-100:]
410 self.shell.db['dhist'] = compress_dhist(dhist)[-100:]
411
411
412 else:
412 else:
413 os.chdir(self.shell.home_dir)
413 os.chdir(self.shell.home_dir)
414 if hasattr(self.shell, 'term_title') and self.shell.term_title:
414 if hasattr(self.shell, 'term_title') and self.shell.term_title:
415 set_term_title(self.shell.term_title_format.format(cwd="~"))
415 set_term_title(self.shell.term_title_format.format(cwd="~"))
416 cwd = os.getcwd()
416 cwd = os.getcwd()
417 dhist = self.shell.user_ns['_dh']
417 dhist = self.shell.user_ns['_dh']
418
418
419 if oldcwd != cwd:
419 if oldcwd != cwd:
420 dhist.append(cwd)
420 dhist.append(cwd)
421 self.shell.db['dhist'] = compress_dhist(dhist)[-100:]
421 self.shell.db['dhist'] = compress_dhist(dhist)[-100:]
422 if not 'q' in opts and not self.cd_force_quiet and self.shell.user_ns['_dh']:
422 if not 'q' in opts and not self.cd_force_quiet and self.shell.user_ns['_dh']:
423 print(self.shell.user_ns['_dh'][-1])
423 print(self.shell.user_ns['_dh'][-1])
424
424
425 @line_magic
425 @line_magic
426 def env(self, parameter_s=''):
426 def env(self, parameter_s=''):
427 """Get, set, or list environment variables.
427 """Get, set, or list environment variables.
428
428
429 Usage:\\
429 Usage:\\
430
430
431 %env: lists all environment variables/values
431 %env: lists all environment variables/values
432 %env var: get value for var
432 %env var: get value for var
433 %env var val: set value for var
433 %env var val: set value for var
434 %env var=val: set value for var
434 %env var=val: set value for var
435 %env var=$val: set value for var, using python expansion if possible
435 %env var=$val: set value for var, using python expansion if possible
436 """
436 """
437 if parameter_s.strip():
437 if parameter_s.strip():
438 split = '=' if '=' in parameter_s else ' '
438 split = '=' if '=' in parameter_s else ' '
439 bits = parameter_s.split(split)
439 bits = parameter_s.split(split)
440 if len(bits) == 1:
440 if len(bits) == 1:
441 key = parameter_s.strip()
441 key = parameter_s.strip()
442 if key in os.environ:
442 if key in os.environ:
443 return os.environ[key]
443 return os.environ[key]
444 else:
444 else:
445 err = "Environment does not have key: {0}".format(key)
445 err = "Environment does not have key: {0}".format(key)
446 raise UsageError(err)
446 raise UsageError(err)
447 if len(bits) > 1:
447 if len(bits) > 1:
448 return self.set_env(parameter_s)
448 return self.set_env(parameter_s)
449 env = dict(os.environ)
449 env = dict(os.environ)
450 # hide likely secrets when printing the whole environment
450 # hide likely secrets when printing the whole environment
451 for key in list(env):
451 for key in list(env):
452 if any(s in key.lower() for s in ('key', 'token', 'secret')):
452 if any(s in key.lower() for s in ('key', 'token', 'secret')):
453 env[key] = '<hidden>'
453 env[key] = '<hidden>'
454
454
455 return env
455 return env
456
456
457 @line_magic
457 @line_magic
458 def set_env(self, parameter_s):
458 def set_env(self, parameter_s):
459 """Set environment variables. Assumptions are that either "val" is a
459 """Set environment variables. Assumptions are that either "val" is a
460 name in the user namespace, or val is something that evaluates to a
460 name in the user namespace, or val is something that evaluates to a
461 string.
461 string.
462
462
463 Usage:\\
463 Usage:\\
464 %set_env var val: set value for var
464 %set_env var val: set value for var
465 %set_env var=val: set value for var
465 %set_env var=val: set value for var
466 %set_env var=$val: set value for var, using python expansion if possible
466 %set_env var=$val: set value for var, using python expansion if possible
467 """
467 """
468 split = '=' if '=' in parameter_s else ' '
468 split = '=' if '=' in parameter_s else ' '
469 bits = parameter_s.split(split, 1)
469 bits = parameter_s.split(split, 1)
470 if not parameter_s.strip() or len(bits)<2:
470 if not parameter_s.strip() or len(bits)<2:
471 raise UsageError("usage is 'set_env var=val'")
471 raise UsageError("usage is 'set_env var=val'")
472 var = bits[0].strip()
472 var = bits[0].strip()
473 val = bits[1].strip()
473 val = bits[1].strip()
474 if re.match(r'.*\s.*', var):
474 if re.match(r'.*\s.*', var):
475 # an environment variable with whitespace is almost certainly
475 # an environment variable with whitespace is almost certainly
476 # not what the user intended. what's more likely is the wrong
476 # not what the user intended. what's more likely is the wrong
477 # split was chosen, ie for "set_env cmd_args A=B", we chose
477 # split was chosen, ie for "set_env cmd_args A=B", we chose
478 # '=' for the split and should have chosen ' '. to get around
478 # '=' for the split and should have chosen ' '. to get around
479 # this, users should just assign directly to os.environ or use
479 # this, users should just assign directly to os.environ or use
480 # standard magic {var} expansion.
480 # standard magic {var} expansion.
481 err = "refusing to set env var with whitespace: '{0}'"
481 err = "refusing to set env var with whitespace: '{0}'"
482 err = err.format(val)
482 err = err.format(val)
483 raise UsageError(err)
483 raise UsageError(err)
484 os.environ[var] = val
484 os.environ[var] = val
485 print('env: {0}={1}'.format(var,val))
485 print('env: {0}={1}'.format(var,val))
486
486
487 @line_magic
487 @line_magic
488 def pushd(self, parameter_s=''):
488 def pushd(self, parameter_s=''):
489 """Place the current dir on stack and change directory.
489 """Place the current dir on stack and change directory.
490
490
491 Usage:\\
491 Usage:\\
492 %pushd ['dirname']
492 %pushd ['dirname']
493 """
493 """
494
494
495 dir_s = self.shell.dir_stack
495 dir_s = self.shell.dir_stack
496 tgt = os.path.expanduser(parameter_s)
496 tgt = os.path.expanduser(parameter_s)
497 cwd = os.getcwd().replace(self.shell.home_dir,'~')
497 cwd = os.getcwd().replace(self.shell.home_dir,'~')
498 if tgt:
498 if tgt:
499 self.cd(parameter_s)
499 self.cd(parameter_s)
500 dir_s.insert(0,cwd)
500 dir_s.insert(0,cwd)
501 return self.shell.magic('dirs')
501 return self.shell.run_line_magic('dirs', '')
502
502
503 @line_magic
503 @line_magic
504 def popd(self, parameter_s=''):
504 def popd(self, parameter_s=''):
505 """Change to directory popped off the top of the stack.
505 """Change to directory popped off the top of the stack.
506 """
506 """
507 if not self.shell.dir_stack:
507 if not self.shell.dir_stack:
508 raise UsageError("%popd on empty stack")
508 raise UsageError("%popd on empty stack")
509 top = self.shell.dir_stack.pop(0)
509 top = self.shell.dir_stack.pop(0)
510 self.cd(top)
510 self.cd(top)
511 print("popd ->",top)
511 print("popd ->",top)
512
512
513 @line_magic
513 @line_magic
514 def dirs(self, parameter_s=''):
514 def dirs(self, parameter_s=''):
515 """Return the current directory stack."""
515 """Return the current directory stack."""
516
516
517 return self.shell.dir_stack
517 return self.shell.dir_stack
518
518
519 @line_magic
519 @line_magic
520 def dhist(self, parameter_s=''):
520 def dhist(self, parameter_s=''):
521 """Print your history of visited directories.
521 """Print your history of visited directories.
522
522
523 %dhist -> print full history\\
523 %dhist -> print full history\\
524 %dhist n -> print last n entries only\\
524 %dhist n -> print last n entries only\\
525 %dhist n1 n2 -> print entries between n1 and n2 (n2 not included)\\
525 %dhist n1 n2 -> print entries between n1 and n2 (n2 not included)\\
526
526
527 This history is automatically maintained by the %cd command, and
527 This history is automatically maintained by the %cd command, and
528 always available as the global list variable _dh. You can use %cd -<n>
528 always available as the global list variable _dh. You can use %cd -<n>
529 to go to directory number <n>.
529 to go to directory number <n>.
530
530
531 Note that most of time, you should view directory history by entering
531 Note that most of time, you should view directory history by entering
532 cd -<TAB>.
532 cd -<TAB>.
533
533
534 """
534 """
535
535
536 dh = self.shell.user_ns['_dh']
536 dh = self.shell.user_ns['_dh']
537 if parameter_s:
537 if parameter_s:
538 try:
538 try:
539 args = map(int,parameter_s.split())
539 args = map(int,parameter_s.split())
540 except:
540 except:
541 self.arg_err(self.dhist)
541 self.arg_err(self.dhist)
542 return
542 return
543 if len(args) == 1:
543 if len(args) == 1:
544 ini,fin = max(len(dh)-(args[0]),0),len(dh)
544 ini,fin = max(len(dh)-(args[0]),0),len(dh)
545 elif len(args) == 2:
545 elif len(args) == 2:
546 ini,fin = args
546 ini,fin = args
547 fin = min(fin, len(dh))
547 fin = min(fin, len(dh))
548 else:
548 else:
549 self.arg_err(self.dhist)
549 self.arg_err(self.dhist)
550 return
550 return
551 else:
551 else:
552 ini,fin = 0,len(dh)
552 ini,fin = 0,len(dh)
553 print('Directory history (kept in _dh)')
553 print('Directory history (kept in _dh)')
554 for i in range(ini, fin):
554 for i in range(ini, fin):
555 print("%d: %s" % (i, dh[i]))
555 print("%d: %s" % (i, dh[i]))
556
556
557 @skip_doctest
557 @skip_doctest
558 @line_magic
558 @line_magic
559 def sc(self, parameter_s=''):
559 def sc(self, parameter_s=''):
560 """Shell capture - run shell command and capture output (DEPRECATED use !).
560 """Shell capture - run shell command and capture output (DEPRECATED use !).
561
561
562 DEPRECATED. Suboptimal, retained for backwards compatibility.
562 DEPRECATED. Suboptimal, retained for backwards compatibility.
563
563
564 You should use the form 'var = !command' instead. Example:
564 You should use the form 'var = !command' instead. Example:
565
565
566 "%sc -l myfiles = ls ~" should now be written as
566 "%sc -l myfiles = ls ~" should now be written as
567
567
568 "myfiles = !ls ~"
568 "myfiles = !ls ~"
569
569
570 myfiles.s, myfiles.l and myfiles.n still apply as documented
570 myfiles.s, myfiles.l and myfiles.n still apply as documented
571 below.
571 below.
572
572
573 --
573 --
574 %sc [options] varname=command
574 %sc [options] varname=command
575
575
576 IPython will run the given command using commands.getoutput(), and
576 IPython will run the given command using commands.getoutput(), and
577 will then update the user's interactive namespace with a variable
577 will then update the user's interactive namespace with a variable
578 called varname, containing the value of the call. Your command can
578 called varname, containing the value of the call. Your command can
579 contain shell wildcards, pipes, etc.
579 contain shell wildcards, pipes, etc.
580
580
581 The '=' sign in the syntax is mandatory, and the variable name you
581 The '=' sign in the syntax is mandatory, and the variable name you
582 supply must follow Python's standard conventions for valid names.
582 supply must follow Python's standard conventions for valid names.
583
583
584 (A special format without variable name exists for internal use)
584 (A special format without variable name exists for internal use)
585
585
586 Options:
586 Options:
587
587
588 -l: list output. Split the output on newlines into a list before
588 -l: list output. Split the output on newlines into a list before
589 assigning it to the given variable. By default the output is stored
589 assigning it to the given variable. By default the output is stored
590 as a single string.
590 as a single string.
591
591
592 -v: verbose. Print the contents of the variable.
592 -v: verbose. Print the contents of the variable.
593
593
594 In most cases you should not need to split as a list, because the
594 In most cases you should not need to split as a list, because the
595 returned value is a special type of string which can automatically
595 returned value is a special type of string which can automatically
596 provide its contents either as a list (split on newlines) or as a
596 provide its contents either as a list (split on newlines) or as a
597 space-separated string. These are convenient, respectively, either
597 space-separated string. These are convenient, respectively, either
598 for sequential processing or to be passed to a shell command.
598 for sequential processing or to be passed to a shell command.
599
599
600 For example::
600 For example::
601
601
602 # Capture into variable a
602 # Capture into variable a
603 In [1]: sc a=ls *py
603 In [1]: sc a=ls *py
604
604
605 # a is a string with embedded newlines
605 # a is a string with embedded newlines
606 In [2]: a
606 In [2]: a
607 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
607 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
608
608
609 # which can be seen as a list:
609 # which can be seen as a list:
610 In [3]: a.l
610 In [3]: a.l
611 Out[3]: ['setup.py', 'win32_manual_post_install.py']
611 Out[3]: ['setup.py', 'win32_manual_post_install.py']
612
612
613 # or as a whitespace-separated string:
613 # or as a whitespace-separated string:
614 In [4]: a.s
614 In [4]: a.s
615 Out[4]: 'setup.py win32_manual_post_install.py'
615 Out[4]: 'setup.py win32_manual_post_install.py'
616
616
617 # a.s is useful to pass as a single command line:
617 # a.s is useful to pass as a single command line:
618 In [5]: !wc -l $a.s
618 In [5]: !wc -l $a.s
619 146 setup.py
619 146 setup.py
620 130 win32_manual_post_install.py
620 130 win32_manual_post_install.py
621 276 total
621 276 total
622
622
623 # while the list form is useful to loop over:
623 # while the list form is useful to loop over:
624 In [6]: for f in a.l:
624 In [6]: for f in a.l:
625 ...: !wc -l $f
625 ...: !wc -l $f
626 ...:
626 ...:
627 146 setup.py
627 146 setup.py
628 130 win32_manual_post_install.py
628 130 win32_manual_post_install.py
629
629
630 Similarly, the lists returned by the -l option are also special, in
630 Similarly, the lists returned by the -l option are also special, in
631 the sense that you can equally invoke the .s attribute on them to
631 the sense that you can equally invoke the .s attribute on them to
632 automatically get a whitespace-separated string from their contents::
632 automatically get a whitespace-separated string from their contents::
633
633
634 In [7]: sc -l b=ls *py
634 In [7]: sc -l b=ls *py
635
635
636 In [8]: b
636 In [8]: b
637 Out[8]: ['setup.py', 'win32_manual_post_install.py']
637 Out[8]: ['setup.py', 'win32_manual_post_install.py']
638
638
639 In [9]: b.s
639 In [9]: b.s
640 Out[9]: 'setup.py win32_manual_post_install.py'
640 Out[9]: 'setup.py win32_manual_post_install.py'
641
641
642 In summary, both the lists and strings used for output capture have
642 In summary, both the lists and strings used for output capture have
643 the following special attributes::
643 the following special attributes::
644
644
645 .l (or .list) : value as list.
645 .l (or .list) : value as list.
646 .n (or .nlstr): value as newline-separated string.
646 .n (or .nlstr): value as newline-separated string.
647 .s (or .spstr): value as space-separated string.
647 .s (or .spstr): value as space-separated string.
648 """
648 """
649
649
650 opts,args = self.parse_options(parameter_s, 'lv')
650 opts,args = self.parse_options(parameter_s, 'lv')
651 # Try to get a variable name and command to run
651 # Try to get a variable name and command to run
652 try:
652 try:
653 # the variable name must be obtained from the parse_options
653 # the variable name must be obtained from the parse_options
654 # output, which uses shlex.split to strip options out.
654 # output, which uses shlex.split to strip options out.
655 var,_ = args.split('=', 1)
655 var,_ = args.split('=', 1)
656 var = var.strip()
656 var = var.strip()
657 # But the command has to be extracted from the original input
657 # But the command has to be extracted from the original input
658 # parameter_s, not on what parse_options returns, to avoid the
658 # parameter_s, not on what parse_options returns, to avoid the
659 # quote stripping which shlex.split performs on it.
659 # quote stripping which shlex.split performs on it.
660 _,cmd = parameter_s.split('=', 1)
660 _,cmd = parameter_s.split('=', 1)
661 except ValueError:
661 except ValueError:
662 var,cmd = '',''
662 var,cmd = '',''
663 # If all looks ok, proceed
663 # If all looks ok, proceed
664 split = 'l' in opts
664 split = 'l' in opts
665 out = self.shell.getoutput(cmd, split=split)
665 out = self.shell.getoutput(cmd, split=split)
666 if 'v' in opts:
666 if 'v' in opts:
667 print('%s ==\n%s' % (var, pformat(out)))
667 print('%s ==\n%s' % (var, pformat(out)))
668 if var:
668 if var:
669 self.shell.user_ns.update({var:out})
669 self.shell.user_ns.update({var:out})
670 else:
670 else:
671 return out
671 return out
672
672
673 @line_cell_magic
673 @line_cell_magic
674 def sx(self, line='', cell=None):
674 def sx(self, line='', cell=None):
675 """Shell execute - run shell command and capture output (!! is short-hand).
675 """Shell execute - run shell command and capture output (!! is short-hand).
676
676
677 %sx command
677 %sx command
678
678
679 IPython will run the given command using commands.getoutput(), and
679 IPython will run the given command using commands.getoutput(), and
680 return the result formatted as a list (split on '\\n'). Since the
680 return the result formatted as a list (split on '\\n'). Since the
681 output is _returned_, it will be stored in ipython's regular output
681 output is _returned_, it will be stored in ipython's regular output
682 cache Out[N] and in the '_N' automatic variables.
682 cache Out[N] and in the '_N' automatic variables.
683
683
684 Notes:
684 Notes:
685
685
686 1) If an input line begins with '!!', then %sx is automatically
686 1) If an input line begins with '!!', then %sx is automatically
687 invoked. That is, while::
687 invoked. That is, while::
688
688
689 !ls
689 !ls
690
690
691 causes ipython to simply issue system('ls'), typing::
691 causes ipython to simply issue system('ls'), typing::
692
692
693 !!ls
693 !!ls
694
694
695 is a shorthand equivalent to::
695 is a shorthand equivalent to::
696
696
697 %sx ls
697 %sx ls
698
698
699 2) %sx differs from %sc in that %sx automatically splits into a list,
699 2) %sx differs from %sc in that %sx automatically splits into a list,
700 like '%sc -l'. The reason for this is to make it as easy as possible
700 like '%sc -l'. The reason for this is to make it as easy as possible
701 to process line-oriented shell output via further python commands.
701 to process line-oriented shell output via further python commands.
702 %sc is meant to provide much finer control, but requires more
702 %sc is meant to provide much finer control, but requires more
703 typing.
703 typing.
704
704
705 3) Just like %sc -l, this is a list with special attributes:
705 3) Just like %sc -l, this is a list with special attributes:
706 ::
706 ::
707
707
708 .l (or .list) : value as list.
708 .l (or .list) : value as list.
709 .n (or .nlstr): value as newline-separated string.
709 .n (or .nlstr): value as newline-separated string.
710 .s (or .spstr): value as whitespace-separated string.
710 .s (or .spstr): value as whitespace-separated string.
711
711
712 This is very useful when trying to use such lists as arguments to
712 This is very useful when trying to use such lists as arguments to
713 system commands."""
713 system commands."""
714
714
715 if cell is None:
715 if cell is None:
716 # line magic
716 # line magic
717 return self.shell.getoutput(line)
717 return self.shell.getoutput(line)
718 else:
718 else:
719 opts,args = self.parse_options(line, '', 'out=')
719 opts,args = self.parse_options(line, '', 'out=')
720 output = self.shell.getoutput(cell)
720 output = self.shell.getoutput(cell)
721 out_name = opts.get('out', opts.get('o'))
721 out_name = opts.get('out', opts.get('o'))
722 if out_name:
722 if out_name:
723 self.shell.user_ns[out_name] = output
723 self.shell.user_ns[out_name] = output
724 else:
724 else:
725 return output
725 return output
726
726
727 system = line_cell_magic('system')(sx)
727 system = line_cell_magic('system')(sx)
728 bang = cell_magic('!')(sx)
728 bang = cell_magic('!')(sx)
729
729
730 @line_magic
730 @line_magic
731 def bookmark(self, parameter_s=''):
731 def bookmark(self, parameter_s=''):
732 """Manage IPython's bookmark system.
732 """Manage IPython's bookmark system.
733
733
734 %bookmark <name> - set bookmark to current dir
734 %bookmark <name> - set bookmark to current dir
735 %bookmark <name> <dir> - set bookmark to <dir>
735 %bookmark <name> <dir> - set bookmark to <dir>
736 %bookmark -l - list all bookmarks
736 %bookmark -l - list all bookmarks
737 %bookmark -d <name> - remove bookmark
737 %bookmark -d <name> - remove bookmark
738 %bookmark -r - remove all bookmarks
738 %bookmark -r - remove all bookmarks
739
739
740 You can later on access a bookmarked folder with::
740 You can later on access a bookmarked folder with::
741
741
742 %cd -b <name>
742 %cd -b <name>
743
743
744 or simply '%cd <name>' if there is no directory called <name> AND
744 or simply '%cd <name>' if there is no directory called <name> AND
745 there is such a bookmark defined.
745 there is such a bookmark defined.
746
746
747 Your bookmarks persist through IPython sessions, but they are
747 Your bookmarks persist through IPython sessions, but they are
748 associated with each profile."""
748 associated with each profile."""
749
749
750 opts,args = self.parse_options(parameter_s,'drl',mode='list')
750 opts,args = self.parse_options(parameter_s,'drl',mode='list')
751 if len(args) > 2:
751 if len(args) > 2:
752 raise UsageError("%bookmark: too many arguments")
752 raise UsageError("%bookmark: too many arguments")
753
753
754 bkms = self.shell.db.get('bookmarks',{})
754 bkms = self.shell.db.get('bookmarks',{})
755
755
756 if 'd' in opts:
756 if 'd' in opts:
757 try:
757 try:
758 todel = args[0]
758 todel = args[0]
759 except IndexError:
759 except IndexError:
760 raise UsageError(
760 raise UsageError(
761 "%bookmark -d: must provide a bookmark to delete")
761 "%bookmark -d: must provide a bookmark to delete")
762 else:
762 else:
763 try:
763 try:
764 del bkms[todel]
764 del bkms[todel]
765 except KeyError:
765 except KeyError:
766 raise UsageError(
766 raise UsageError(
767 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
767 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
768
768
769 elif 'r' in opts:
769 elif 'r' in opts:
770 bkms = {}
770 bkms = {}
771 elif 'l' in opts:
771 elif 'l' in opts:
772 bks = sorted(bkms)
772 bks = sorted(bkms)
773 if bks:
773 if bks:
774 size = max(map(len, bks))
774 size = max(map(len, bks))
775 else:
775 else:
776 size = 0
776 size = 0
777 fmt = '%-'+str(size)+'s -> %s'
777 fmt = '%-'+str(size)+'s -> %s'
778 print('Current bookmarks:')
778 print('Current bookmarks:')
779 for bk in bks:
779 for bk in bks:
780 print(fmt % (bk, bkms[bk]))
780 print(fmt % (bk, bkms[bk]))
781 else:
781 else:
782 if not args:
782 if not args:
783 raise UsageError("%bookmark: You must specify the bookmark name")
783 raise UsageError("%bookmark: You must specify the bookmark name")
784 elif len(args)==1:
784 elif len(args)==1:
785 bkms[args[0]] = os.getcwd()
785 bkms[args[0]] = os.getcwd()
786 elif len(args)==2:
786 elif len(args)==2:
787 bkms[args[0]] = args[1]
787 bkms[args[0]] = args[1]
788 self.shell.db['bookmarks'] = bkms
788 self.shell.db['bookmarks'] = bkms
789
789
790 @line_magic
790 @line_magic
791 def pycat(self, parameter_s=''):
791 def pycat(self, parameter_s=''):
792 """Show a syntax-highlighted file through a pager.
792 """Show a syntax-highlighted file through a pager.
793
793
794 This magic is similar to the cat utility, but it will assume the file
794 This magic is similar to the cat utility, but it will assume the file
795 to be Python source and will show it with syntax highlighting.
795 to be Python source and will show it with syntax highlighting.
796
796
797 This magic command can either take a local filename, an url,
797 This magic command can either take a local filename, an url,
798 an history range (see %history) or a macro as argument ::
798 an history range (see %history) or a macro as argument ::
799
799
800 %pycat myscript.py
800 %pycat myscript.py
801 %pycat 7-27
801 %pycat 7-27
802 %pycat myMacro
802 %pycat myMacro
803 %pycat http://www.example.com/myscript.py
803 %pycat http://www.example.com/myscript.py
804 """
804 """
805 if not parameter_s:
805 if not parameter_s:
806 raise UsageError('Missing filename, URL, input history range, '
806 raise UsageError('Missing filename, URL, input history range, '
807 'or macro.')
807 'or macro.')
808
808
809 try :
809 try :
810 cont = self.shell.find_user_code(parameter_s, skip_encoding_cookie=False)
810 cont = self.shell.find_user_code(parameter_s, skip_encoding_cookie=False)
811 except (ValueError, IOError):
811 except (ValueError, IOError):
812 print("Error: no such file, variable, URL, history range or macro")
812 print("Error: no such file, variable, URL, history range or macro")
813 return
813 return
814
814
815 page.page(self.shell.pycolorize(source_to_unicode(cont)))
815 page.page(self.shell.pycolorize(source_to_unicode(cont)))
816
816
817 @magic_arguments.magic_arguments()
817 @magic_arguments.magic_arguments()
818 @magic_arguments.argument(
818 @magic_arguments.argument(
819 '-a', '--append', action='store_true', default=False,
819 '-a', '--append', action='store_true', default=False,
820 help='Append contents of the cell to an existing file. '
820 help='Append contents of the cell to an existing file. '
821 'The file will be created if it does not exist.'
821 'The file will be created if it does not exist.'
822 )
822 )
823 @magic_arguments.argument(
823 @magic_arguments.argument(
824 'filename', type=str,
824 'filename', type=str,
825 help='file to write'
825 help='file to write'
826 )
826 )
827 @cell_magic
827 @cell_magic
828 def writefile(self, line, cell):
828 def writefile(self, line, cell):
829 """Write the contents of the cell to a file.
829 """Write the contents of the cell to a file.
830
830
831 The file will be overwritten unless the -a (--append) flag is specified.
831 The file will be overwritten unless the -a (--append) flag is specified.
832 """
832 """
833 args = magic_arguments.parse_argstring(self.writefile, line)
833 args = magic_arguments.parse_argstring(self.writefile, line)
834 if re.match(r'^(\'.*\')|(".*")$', args.filename):
834 if re.match(r'^(\'.*\')|(".*")$', args.filename):
835 filename = os.path.expanduser(args.filename[1:-1])
835 filename = os.path.expanduser(args.filename[1:-1])
836 else:
836 else:
837 filename = os.path.expanduser(args.filename)
837 filename = os.path.expanduser(args.filename)
838
838
839 if os.path.exists(filename):
839 if os.path.exists(filename):
840 if args.append:
840 if args.append:
841 print("Appending to %s" % filename)
841 print("Appending to %s" % filename)
842 else:
842 else:
843 print("Overwriting %s" % filename)
843 print("Overwriting %s" % filename)
844 else:
844 else:
845 print("Writing %s" % filename)
845 print("Writing %s" % filename)
846
846
847 mode = 'a' if args.append else 'w'
847 mode = 'a' if args.append else 'w'
848 with io.open(filename, mode, encoding='utf-8') as f:
848 with io.open(filename, mode, encoding='utf-8') as f:
849 f.write(cell)
849 f.write(cell)
General Comments 0
You need to be logged in to leave comments. Login now