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