Import a Python module from a path, and run the function given by name, if function_name is not None.
(code, code_path, ns=None, function_name=None)
| 550 | |
| 551 | |
| 552 | def _run_code(code, code_path, ns=None, function_name=None): |
| 553 | """ |
| 554 | Import a Python module from a path, and run the function given by |
| 555 | name, if function_name is not None. |
| 556 | """ |
| 557 | |
| 558 | # Change the working directory to the directory of the example, so |
| 559 | # it can get at its data files, if any. Add its path to sys.path |
| 560 | # so it can import any helper modules sitting beside it. |
| 561 | pwd = os.getcwd() |
| 562 | if setup.config.plot_working_directory is not None: |
| 563 | try: |
| 564 | os.chdir(setup.config.plot_working_directory) |
| 565 | except OSError as err: |
| 566 | raise OSError(f'{err}\n`plot_working_directory` option in ' |
| 567 | f'Sphinx configuration file must be a valid ' |
| 568 | f'directory path') from err |
| 569 | except TypeError as err: |
| 570 | raise TypeError(f'{err}\n`plot_working_directory` option in ' |
| 571 | f'Sphinx configuration file must be a string or ' |
| 572 | f'None') from err |
| 573 | elif code_path is not None: |
| 574 | dirname = os.path.abspath(os.path.dirname(code_path)) |
| 575 | os.chdir(dirname) |
| 576 | |
| 577 | with cbook._setattr_cm( |
| 578 | sys, argv=[code_path], path=[os.getcwd(), *sys.path]), \ |
| 579 | contextlib.redirect_stdout(StringIO()): |
| 580 | try: |
| 581 | if ns is None: |
| 582 | ns = {} |
| 583 | if not ns: |
| 584 | if setup.config.plot_pre_code is None: |
| 585 | exec('import numpy as np\n' |
| 586 | 'from matplotlib import pyplot as plt\n', ns) |
| 587 | else: |
| 588 | exec(str(setup.config.plot_pre_code), ns) |
| 589 | if "__main__" in code: |
| 590 | ns['__name__'] = '__main__' |
| 591 | |
| 592 | # Patch out non-interactive show() to avoid triggering a warning. |
| 593 | with cbook._setattr_cm(FigureManagerBase, show=lambda self: None): |
| 594 | exec(code, ns) |
| 595 | if function_name is not None: |
| 596 | exec(function_name + "()", ns) |
| 597 | |
| 598 | except (Exception, SystemExit) as err: |
| 599 | raise PlotError(traceback.format_exc()) from err |
| 600 | finally: |
| 601 | os.chdir(pwd) |
| 602 | return ns |
| 603 | |
| 604 | |
| 605 | def clear_state(plot_rcparams, close=True): |
no test coverage detected
searching dependent graphs…