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