osm.py 28 KB

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