Skip to content

New approach for the whole extension #9

@romintomasetti

Description

@romintomasetti

Welcome to ProposedPatch's documentation!

Preliminary remark

From the pip3 install sphinx-execute-code, we must change the __init__.py
file so that it is python3-compliant.

.. code-block:: python

exec(code)

if sys.version[0] == 2:
    from StringIO import StringIO
else:
    from io import StringIO

output = StringIO()
err = StringIO()

Why is it necessary to change the approach followed initially in this extension?

The execute_code directive, as it is implemented in the pip3 package, is not suitable for
a lot of user cases.

Indeed, since exec is used for executing the code, it has the following limitations:

* Only `Python` code, compliant with the python version of `Sphinx`, can be used.
  `Python3` codes can't be executed if `Sphinx` uses `Python2` and vice-versa.
* Only `Python` codes can be executed (because of the use of `exec`).
* In some cases, using twice the `execute_code` directive can lead to unexpected results.
  For instance, if `execute_code` is called twice, and in each code snippet there is::

    import logging
    logging.basicConfig(level=logging.DEBUG)

  the behviour is such that any log message of the first `execute_code` call is catched, but none
  of the log messages of the second `execute_code` is catched. This is due to the `logging`
  module of course. That behaviour come out of the code snippets being executed via `exec`.
  See the :class:`codes.Example`.

Proposed approach

Use the subprocess package to execute the code snippets. Advantages of the approach:

* One can specify the code snippet `input language`, enabling `Python2` snippets to
  be exectuted with `Sphinx` that uses `Python3`, and vice-versa.
* Other interpreted languages could easily be executed.
* Since each code snippet is executed in subprocesses, the problem with the `logging`
  module does not occur anymore.

The only problem I see at the moment is that if the Python code is not correct,
it won't raise any error and Sphinx will not stop.

Attached files

Please find in the attachments all necessary files to build a simple Sphinx doc and
test the changes.

Example documentation

.. automodule:: codes

Additional information

Version of Sphinx::

sphinx-build 2.2.1

proposed_new_extension.zip

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions