script.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. """Magic functions for running cells in various scripts."""
  2. from __future__ import print_function
  3. # Copyright (c) IPython Development Team.
  4. # Distributed under the terms of the Modified BSD License.
  5. import errno
  6. import os
  7. import sys
  8. import signal
  9. import time
  10. from subprocess import Popen, PIPE
  11. import atexit
  12. from IPython.core import magic_arguments
  13. from IPython.core.magic import (
  14. Magics, magics_class, line_magic, cell_magic
  15. )
  16. from IPython.lib.backgroundjobs import BackgroundJobManager
  17. from IPython.utils import py3compat
  18. from IPython.utils.process import arg_split
  19. from traitlets import List, Dict, default
  20. #-----------------------------------------------------------------------------
  21. # Magic implementation classes
  22. #-----------------------------------------------------------------------------
  23. def script_args(f):
  24. """single decorator for adding script args"""
  25. args = [
  26. magic_arguments.argument(
  27. '--out', type=str,
  28. help="""The variable in which to store stdout from the script.
  29. If the script is backgrounded, this will be the stdout *pipe*,
  30. instead of the stderr text itself.
  31. """
  32. ),
  33. magic_arguments.argument(
  34. '--err', type=str,
  35. help="""The variable in which to store stderr from the script.
  36. If the script is backgrounded, this will be the stderr *pipe*,
  37. instead of the stderr text itself.
  38. """
  39. ),
  40. magic_arguments.argument(
  41. '--bg', action="store_true",
  42. help="""Whether to run the script in the background.
  43. If given, the only way to see the output of the command is
  44. with --out/err.
  45. """
  46. ),
  47. magic_arguments.argument(
  48. '--proc', type=str,
  49. help="""The variable in which to store Popen instance.
  50. This is used only when --bg option is given.
  51. """
  52. ),
  53. ]
  54. for arg in args:
  55. f = arg(f)
  56. return f
  57. @magics_class
  58. class ScriptMagics(Magics):
  59. """Magics for talking to scripts
  60. This defines a base `%%script` cell magic for running a cell
  61. with a program in a subprocess, and registers a few top-level
  62. magics that call %%script with common interpreters.
  63. """
  64. script_magics = List(
  65. help="""Extra script cell magics to define
  66. This generates simple wrappers of `%%script foo` as `%%foo`.
  67. If you want to add script magics that aren't on your path,
  68. specify them in script_paths
  69. """,
  70. ).tag(config=True)
  71. @default('script_magics')
  72. def _script_magics_default(self):
  73. """default to a common list of programs"""
  74. defaults = [
  75. 'sh',
  76. 'bash',
  77. 'perl',
  78. 'ruby',
  79. 'python',
  80. 'python2',
  81. 'python3',
  82. 'pypy',
  83. ]
  84. if os.name == 'nt':
  85. defaults.extend([
  86. 'cmd',
  87. ])
  88. return defaults
  89. script_paths = Dict(
  90. help="""Dict mapping short 'ruby' names to full paths, such as '/opt/secret/bin/ruby'
  91. Only necessary for items in script_magics where the default path will not
  92. find the right interpreter.
  93. """
  94. ).tag(config=True)
  95. def __init__(self, shell=None):
  96. super(ScriptMagics, self).__init__(shell=shell)
  97. self._generate_script_magics()
  98. self.job_manager = BackgroundJobManager()
  99. self.bg_processes = []
  100. atexit.register(self.kill_bg_processes)
  101. def __del__(self):
  102. self.kill_bg_processes()
  103. def _generate_script_magics(self):
  104. cell_magics = self.magics['cell']
  105. for name in self.script_magics:
  106. cell_magics[name] = self._make_script_magic(name)
  107. def _make_script_magic(self, name):
  108. """make a named magic, that calls %%script with a particular program"""
  109. # expand to explicit path if necessary:
  110. script = self.script_paths.get(name, name)
  111. @magic_arguments.magic_arguments()
  112. @script_args
  113. def named_script_magic(line, cell):
  114. # if line, add it as cl-flags
  115. if line:
  116. line = "%s %s" % (script, line)
  117. else:
  118. line = script
  119. return self.shebang(line, cell)
  120. # write a basic docstring:
  121. named_script_magic.__doc__ = \
  122. """%%{name} script magic
  123. Run cells with {script} in a subprocess.
  124. This is a shortcut for `%%script {script}`
  125. """.format(**locals())
  126. return named_script_magic
  127. @magic_arguments.magic_arguments()
  128. @script_args
  129. @cell_magic("script")
  130. def shebang(self, line, cell):
  131. """Run a cell via a shell command
  132. The `%%script` line is like the #! line of script,
  133. specifying a program (bash, perl, ruby, etc.) with which to run.
  134. The rest of the cell is run by that program.
  135. Examples
  136. --------
  137. ::
  138. In [1]: %%script bash
  139. ...: for i in 1 2 3; do
  140. ...: echo $i
  141. ...: done
  142. 1
  143. 2
  144. 3
  145. """
  146. argv = arg_split(line, posix = not sys.platform.startswith('win'))
  147. args, cmd = self.shebang.parser.parse_known_args(argv)
  148. try:
  149. p = Popen(cmd, stdout=PIPE, stderr=PIPE, stdin=PIPE)
  150. except OSError as e:
  151. if e.errno == errno.ENOENT:
  152. print("Couldn't find program: %r" % cmd[0])
  153. return
  154. else:
  155. raise
  156. if not cell.endswith('\n'):
  157. cell += '\n'
  158. cell = cell.encode('utf8', 'replace')
  159. if args.bg:
  160. self.bg_processes.append(p)
  161. self._gc_bg_processes()
  162. if args.out:
  163. self.shell.user_ns[args.out] = p.stdout
  164. if args.err:
  165. self.shell.user_ns[args.err] = p.stderr
  166. self.job_manager.new(self._run_script, p, cell, daemon=True)
  167. if args.proc:
  168. self.shell.user_ns[args.proc] = p
  169. return
  170. try:
  171. out, err = p.communicate(cell)
  172. except KeyboardInterrupt:
  173. try:
  174. p.send_signal(signal.SIGINT)
  175. time.sleep(0.1)
  176. if p.poll() is not None:
  177. print("Process is interrupted.")
  178. return
  179. p.terminate()
  180. time.sleep(0.1)
  181. if p.poll() is not None:
  182. print("Process is terminated.")
  183. return
  184. p.kill()
  185. print("Process is killed.")
  186. except OSError:
  187. pass
  188. except Exception as e:
  189. print("Error while terminating subprocess (pid=%i): %s" \
  190. % (p.pid, e))
  191. return
  192. out = py3compat.bytes_to_str(out)
  193. err = py3compat.bytes_to_str(err)
  194. if args.out:
  195. self.shell.user_ns[args.out] = out
  196. else:
  197. sys.stdout.write(out)
  198. sys.stdout.flush()
  199. if args.err:
  200. self.shell.user_ns[args.err] = err
  201. else:
  202. sys.stderr.write(err)
  203. sys.stderr.flush()
  204. def _run_script(self, p, cell):
  205. """callback for running the script in the background"""
  206. p.stdin.write(cell)
  207. p.stdin.close()
  208. p.wait()
  209. @line_magic("killbgscripts")
  210. def killbgscripts(self, _nouse_=''):
  211. """Kill all BG processes started by %%script and its family."""
  212. self.kill_bg_processes()
  213. print("All background processes were killed.")
  214. def kill_bg_processes(self):
  215. """Kill all BG processes which are still running."""
  216. for p in self.bg_processes:
  217. if p.poll() is None:
  218. try:
  219. p.send_signal(signal.SIGINT)
  220. except:
  221. pass
  222. time.sleep(0.1)
  223. for p in self.bg_processes:
  224. if p.poll() is None:
  225. try:
  226. p.terminate()
  227. except:
  228. pass
  229. time.sleep(0.1)
  230. for p in self.bg_processes:
  231. if p.poll() is None:
  232. try:
  233. p.kill()
  234. except:
  235. pass
  236. self._gc_bg_processes()
  237. def _gc_bg_processes(self):
  238. self.bg_processes = [p for p in self.bg_processes if p.poll() is None]