PageRenderTime 59ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/IPython/core/magics/osm.py

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