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. .. versionchanged:: 9.0 Interrupting the script executed withou
(self, line, cell)
| 174 | @script_args |
| 175 | @cell_magic("script") |
| 176 | def shebang(self, line, cell): |
| 177 | """Run a cell via a shell command |
| 178 | |
| 179 | The `%%script` line is like the #! line of script, |
| 180 | specifying a program (bash, perl, ruby, etc.) with which to run. |
| 181 | |
| 182 | The rest of the cell is run by that program. |
| 183 | |
| 184 | .. versionchanged:: 9.0 |
| 185 | Interrupting the script executed without `--bg` will end in |
| 186 | raising an exception (unless `--no-raise-error` is passed). |
| 187 | |
| 188 | Examples |
| 189 | -------- |
| 190 | :: |
| 191 | |
| 192 | In [1]: %%script bash |
| 193 | ...: for i in 1 2 3; do |
| 194 | ...: echo $i |
| 195 | ...: done |
| 196 | 1 |
| 197 | 2 |
| 198 | 3 |
| 199 | """ |
| 200 | |
| 201 | # Create the event loop in which to run script magics |
| 202 | # this operates on a background thread |
| 203 | if self.event_loop is None: |
| 204 | if sys.platform == "win32": |
| 205 | # don't override the current policy, |
| 206 | # just create an event loop |
| 207 | event_loop = asyncio.WindowsProactorEventLoopPolicy().new_event_loop() |
| 208 | else: |
| 209 | event_loop = asyncio.new_event_loop() |
| 210 | self.event_loop = event_loop |
| 211 | |
| 212 | # start the loop in a background thread |
| 213 | asyncio_thread = Thread(target=event_loop.run_forever, daemon=True) |
| 214 | asyncio_thread.start() |
| 215 | else: |
| 216 | event_loop = self.event_loop |
| 217 | |
| 218 | def in_thread(coro): |
| 219 | """Call a coroutine on the asyncio thread""" |
| 220 | return asyncio.run_coroutine_threadsafe(coro, event_loop).result() |
| 221 | |
| 222 | async def _readchunk(stream): |
| 223 | try: |
| 224 | return await stream.read(100) |
| 225 | except asyncio.exceptions.IncompleteReadError as e: |
| 226 | return e.partial |
| 227 | except asyncio.exceptions.LimitOverrunError as e: |
| 228 | return await stream.read(e.consumed) |
| 229 | |
| 230 | async def _handle_stream(stream, stream_arg, file_object): |
| 231 | should_break = False |
| 232 | decoder = getincrementaldecoder("utf-8")(errors="replace") |
| 233 | while True: |
no test coverage detected