How to Include Python Code From Files in Quarto

Make it possible to import outside code into your quarto notebooks.
Author
Published

August 31, 2024

Modified

August 31, 2024

Keywords

quarto, python, include code, external code, datascience, data, science

It is possible to include code files using the include-code-files extension for quarto. For more on adding extensions, see the documentation about extensions management.

Including Files

First, in the front matter of your quarto document, add

filters:
  - include-code-files

Next, create example.py with the contents

def main():
    print("It works!")


if __name__ == "__main__":
    main()

and ensure that example.py works using

python ./example.py

To include this file in simply do:

```{.python include="example.py"}
```

which should render to

def main():
    print("It works!")


if __name__ == "__main__":
    main()

Running Files

example.py can be run using the run jupyter magic commands like:

%run example.py
It works!

More about magic commands is available in the jupyter documentation. Finally, with main in the local python globals, we can execute main.

main()
It works!

Including Snippets From Files

Often, including the whole file is not desirable and only a part of the file should be included. For instance if the conents of example.py are modified to make it

# start snippet main
def main():
    print("It works!")
    # end snippet main


if __name__ == "__main__":
    main()

the following code block in quarto will only include the main function definition.

```{.python include="eample.py" snippet="print"}
```