Run a cell via a shell command The `%%script` line is like the #! line of script, specifying a program (bash, perl, ruby, etc.) with which to run. The rest of the cell is run by that program. Examples -------- ::
(self, line, cell)
| 156 | @script_args |
| 157 | @cell_magic("script") |
| 158 | def shebang(self, line, cell): |
| 159 | """Run a cell via a shell command |
| 160 | |
| 161 | The `%%script` line is like the #! line of script, |
| 162 | specifying a program (bash, perl, ruby, etc.) with which to run. |
| 163 | |
| 164 | The rest of the cell is run by that program. |
| 165 | |
| 166 | Examples |
| 167 | -------- |
| 168 | :: |
| 169 | |
| 170 | In [1]: %%script bash |
| 171 | ...: for i in 1 2 3; do |
| 172 | ...: echo $i |
| 173 | ...: done |
| 174 | 1 |
| 175 | 2 |
| 176 | 3 |
| 177 | """ |
| 178 | argv = arg_split(line, posix = not sys.platform.startswith('win')) |
| 179 | args, cmd = self.shebang.parser.parse_known_args(argv) |
| 180 | |
| 181 | try: |
| 182 | p = Popen(cmd, stdout=PIPE, stderr=PIPE, stdin=PIPE) |
| 183 | except OSError as e: |
| 184 | if e.errno == errno.ENOENT: |
| 185 | print("Couldn't find program: %r" % cmd[0]) |
| 186 | return |
| 187 | else: |
| 188 | raise |
| 189 | |
| 190 | if not cell.endswith('\n'): |
| 191 | cell += '\n' |
| 192 | cell = cell.encode('utf8', 'replace') |
| 193 | if args.bg: |
| 194 | self.bg_processes.append(p) |
| 195 | self._gc_bg_processes() |
| 196 | to_close = [] |
| 197 | if args.out: |
| 198 | self.shell.user_ns[args.out] = p.stdout |
| 199 | else: |
| 200 | to_close.append(p.stdout) |
| 201 | if args.err: |
| 202 | self.shell.user_ns[args.err] = p.stderr |
| 203 | else: |
| 204 | to_close.append(p.stderr) |
| 205 | self.job_manager.new(self._run_script, p, cell, to_close, daemon=True) |
| 206 | if args.proc: |
| 207 | self.shell.user_ns[args.proc] = p |
| 208 | return |
| 209 | |
| 210 | try: |
| 211 | out, err = p.communicate(cell) |
| 212 | except KeyboardInterrupt: |
| 213 | try: |
| 214 | p.send_signal(signal.SIGINT) |
| 215 | time.sleep(0.1) |
no test coverage detected