Code execution
This can be used for either automation (executing code without showing source code) or tutorials (executing and displaying both results and source code).
To use this feature, you need to install markdown-exec
. See the documentation for more information.
Showing Source Code and Results
tabbed
which was generated by using the markdown code:
Markdown |
---|
| ```python exec="true" source="tabbed-left" result="pycon"
import os, sys
print('cwd',os.getcwd())
```
|
Source Code above
Python |
---|
| import os
print(os.getcwd())
|
Python Console Session |
---|
| D:\Dropbox\Python\SandBox\Mkdocs\SandBox
|
which was run using:
Markdown |
---|
| ```python exec="true" source="above" result="pycon"
import os
print(os.getcwd())
```
|
Running Own Hosted Module in GitHub
This is really cool! With markdown-exec
, you can showcase your own projects hosted on GitHub or insert examples into docstrings, such as the class Two_numbers
.
Here, a Python script imports a class from this project module: sandbox.calculations.Two_numbers
.
which was run using this markdown code:
Markdown |
---|
| ```python exec="true" source="tabbed-left" result="pycon"
from sandbox.calculations import Two_numbers
nums = Two_numbers(4, 2)
print(f'{nums.add()=}')
```
|
Using mkdocs gh-deploy
Manually
- With Poetry, this works out of the box.
- This option uses your local environment, including dependencies and PYTHONPATH.
- Note: This has not been tested without Poetry. You will likely need to install the package in your environment first.
Using GitHub actions
- After pushing changes to the remote repo and prior to deployment, a new environment will be created. In addition to the MkDocs-related dependencies, you should also include the dependencies required to execute your package's code examples.
For this example:
- I modified the
ci.yml
file for GitHub workflows to enable package installation during deployment.
ci.yml |
---|
| - run: pip install git+https://github.com/lennon-c/SandBox_Mkdocs.git
|
- This means that an installation of your own package is required.
- Since I'm using Poetry, I only needed to add the necessary documentation for packaging, and a package wheel was not required.
Prints
Sadly, it cannot capture prints from imported code.
Nothing will be printed in the following two blocks.
It is only able to see prints from functions created in the current session, as in the following code: