def run_code()

in _ext/sphinx_plotly_directive.py [0:0]


def run_code(code, code_path, ns=None, function_name=None, fig_vars=None):
    """
    Import a Python module from a path, and run the function given by
    name, if function_name is not None.
    """

    # Change the working directory to the directory of the example, so
    # it can get at its data files, if any.  Add its path to sys.path
    # so it can import any helper modules sitting beside it.
    pwd = os.getcwd()
    if setup.config.plotly_working_directory is not None:
        try:
            os.chdir(setup.config.plotly_working_directory)
        except OSError as err:
            raise OSError(
                str(err) + "\n`plot_working_directory` option in"
                "Sphinx configuration file must be a valid "
                "directory path"
            ) from err
        except TypeError as err:
            raise TypeError(
                str(err) + "\n`plot_working_directory` option in "
                "Sphinx configuration file must be a string or "
                "None"
            ) from err
    elif code_path is not None:
        dirname = os.path.abspath(os.path.dirname(code_path))
        os.chdir(dirname)

    try:
        code = unescape_doctest(code)
        if ns is None:
            ns = {}
        if not ns:
            if setup.config.plotly_pre_code is None:
                exec(
                    "\n".join(
                        [
                            "import numpy as np",
                            "import plotly",
                            "import plotly.graph_objects as go",
                            "import plotly.express as px",
                        ]
                    ),
                    ns,
                )
            else:
                exec(str(setup.config.plotly_pre_code), ns)
        if "__main__" in code:
            ns["__name__"] = "__main__"

        variable_name = "fig"

        if ends_with_show(code):
            exec(strip_last_line(code), ns)
            figs = [ns[fig_var] for fig_var in fig_vars] if fig_vars else [ns[variable_name]]
        elif function_name is not None:
            exec(code, ns)
            exec(assign_last_line_into_variable(function_name + "()", variable_name), ns)
            figs = [ns[variable_name]]
        elif fig_vars:
            exec(code, ns)
            figs = [ns[fig_var] for fig_var in fig_vars]
        else:
            exec(assign_last_line_into_variable(code, variable_name), ns)
            figs = [ns[variable_name]]

    except (Exception, SystemExit) as err:
        raise PlotError(traceback.format_exc()) from err
    finally:
        os.chdir(pwd)

    return figs