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