Issue
I want to be able to get a multi-line string from a python file and display it in Markdown, so that I don't have to keep updating the Markdown file to match with the file. I'm new to using Markdown, so I don't have much experience with it.
I tried 2 things:
```{python}
import mymodule
print(mymodule.mystring)
```
and
```python
import mymodule
print(mymodule.mystring)
```
I want it to just show the data that mystring
represents, but instead it just displays the python code itself.
Note that mymodule is another file in the same folder, and mystring is a multi-line string in that file.
Solution
Markdown itself is a formatting tool and doesn't run code.
```python
only helps syntax highlight a python code block.
If you want to add data from a python program, you'll need to use an additional tool to run the python!
One option is to create your markdown file with python code. You could do something like this in a generate_markdown.py
file:
import mymodule
mystring = mymodule.mystring
# write code here to generate your markdown file using mystring
Jinja
is a cool tool for this purpose and it's available as the python package Jinja2.
Starting with a markdown template file like example.md.j2
:
Hello {{ data.mystring }}
You can pass this file into Jinja
with mystring
and it will produce example.md
:
Hello World
if mystring
contained the text "World".
Honestly, I remember it taking a bit for me to learn Jinja back when I used it for a project. You can start at thier site and there is also a command line tool as a python package called jinja-cli which is a nice way to get introduced to the tool before you start writing the python that generates your document.
For your usecase, you may skip Jinja all together and do a find and replace in a template file on a placeholder like {{ data.mystring }}
(or anything else like MY_PLACEHOLDER
) to produce your final markdown file. Jinja has more features that you may find useful, but you can also go for something custom and simple if that fits your needs!
A different approach if you want to keep your code inside of your markdown document is to use something like Pweave to generate html containing the output of your ```python
code blocks.
As far as I can tell, Pweave generates html from markdown and so if you need your output to be a markdown file (like the README.md
of a GitHub repository), this might not be the tool for you. It does seem really neat though with the ability for visualizations generated from python code.
Answered By - M Stefan Walker
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.