Executes ``self.code``. Can only be used after calling compile. The code may not use top level await, use :py:meth:`CodeRunner.run_async` for code that uses top level await. Parameters ---------- globals : The global scope in which to ex
(
self,
globals: dict[str, Any] | None = None,
locals: dict[str, Any] | None = None,
)
| 312 | linecache.cache[filename] = [lambda: source] # type:ignore[assignment] |
| 313 | |
| 314 | def run( |
| 315 | self, |
| 316 | globals: dict[str, Any] | None = None, |
| 317 | locals: dict[str, Any] | None = None, |
| 318 | ) -> Any: |
| 319 | """Executes ``self.code``. |
| 320 | |
| 321 | Can only be used after calling compile. The code may not use top level |
| 322 | await, use :py:meth:`CodeRunner.run_async` for code that uses top level |
| 323 | await. |
| 324 | |
| 325 | Parameters |
| 326 | ---------- |
| 327 | globals : |
| 328 | |
| 329 | The global scope in which to execute code. This is used as the ``globals`` |
| 330 | parameter for :py:func:`exec`. If ``globals`` is absent, a new empty dictionary is used. |
| 331 | |
| 332 | locals : |
| 333 | |
| 334 | The local scope in which to execute code. This is used as the ``locals`` |
| 335 | parameter for :py:func:`exec`. If ``locals`` is absent, the value of ``globals`` is |
| 336 | used. |
| 337 | |
| 338 | Returns |
| 339 | ------- |
| 340 | |
| 341 | If the last nonwhitespace character of ``source`` is a semicolon, |
| 342 | return ``None``. If the last statement is an expression, return the |
| 343 | result of the expression. Use the ``return_mode`` and |
| 344 | ``quiet_trailing_semicolon`` parameters to modify this default |
| 345 | behavior. |
| 346 | """ |
| 347 | if globals is None: |
| 348 | globals = {} |
| 349 | if locals is None: |
| 350 | locals = globals |
| 351 | if not self._compiled: |
| 352 | raise RuntimeError("Not yet compiled") |
| 353 | if self.code is None: |
| 354 | return None |
| 355 | self._set_linecache() |
| 356 | try: |
| 357 | coroutine = eval(self.code, globals, locals) |
| 358 | if coroutine: |
| 359 | raise RuntimeError( |
| 360 | "Used eval_code with TOP_LEVEL_AWAIT. Use run_async for this instead." |
| 361 | ) |
| 362 | except EvalCodeResultException as e: |
| 363 | # Final expression from code returns here |
| 364 | return e.value |
| 365 | |
| 366 | return None |
| 367 | |
| 368 | async def run_async( |
| 369 | self, |