Automatic execution of code blocks


Convert this document to ipynb, latex or html with e.g.:

doconce format ipynb execute.do.txt --execute

Code blocks in different languages

Python

Python code

for i in [1,2,3]:
  print(i)
1
2
3
print(i)
3

Bash

Bash code

if [ 1 -eq 1 ] ; then echo 1; fi
var_bash=10
1
echo $var_bash
10

Julia

Julia code

var_julia = 11
print(var_julia)

        
for n = 2:4
  var_julia = var_julia + n
end
print(var_julia)

        

R

R code

x <- 1:3
print(x)
#pdf("plot.pdf")
plot(x)
#dev.off()

        

Other languages

Then Cython (with -h option so it is hidden in html/sphinx):

Java code

for (int i = 0; i < 5; i++) {
  System.out.println(i);
}

Javascript code

for (var x in [0,1,2]) {console.log(x)}

matlab code

for i = 1:2:10
  disp(A(i))
end

html code

<a href='test'></a>

C code

#include <stdio.h>

int main() {
  int i;

  for (i = 1; i < 11; ++i)
  {
    printf("%d ", i);
  }
  return 0;
}

Code block environments

Hidden execution cells (pyhid, pycod-e) can be used to perform operations (e.g. imports, variable initializations) without showing any cell. The pyhid environment executes and hides the cell in formats other than .ipynb:

This is a normal python block using the pycod environment

print('pycod')
pycod

The pycod-e environment executes but hides the cell also in .ipynb files:

pycod is a normal cell that should execute automatically when using --execute. Note that this cells relies on code executed in a previous hidden cell:

print(sys.version)
b = 2
c = a + b
print("The result is {}".format(c))
c
3.9.0 (default, Nov 15 2020, 14:28:56) 
[GCC 7.3.0]
The result is 3
3

Special environments

The *-t environment (e.g. pycod-t) formats a cell to text, and can be used to print an example

# This is a for-loop example
for i in [0,10]:
  print(i)

The *out (e.g. pycod-out) environment can be used to write a cell output:

# This is a text cell using pycod-t
1/0
# This is a output cell using the `pycod-out` environment
1/0: You cannot divide by zero

The -h postfix can be used in the html format to show a Show/Hide button that toggles the code visibility.

The pyscpro environment creates an interactive cell using Sage in the html format

Plotting

This is a cell that should plot and output:

from pylab import *
x = linspace(0, 10, 100)
plot(x, x*x)
show()

PDF cannot be displayed in your browser. See .doconce_figure_cache/bdeb890a-7b85-4e0c-ad01-25d81c7b849e.pdf

We can now refer to this plot as Figure python_plot.

To improve quality when exporting to LaTeX, the following code has automatically been run to enable PDF export in notebooks.

from IPython.display import set_matplotlib_formats
set_matplotlib_formats('png', 'pdf')

Ignore output

Predefined output can be omitted by passing --ignore_output to DocOnce. This will remove all environments ending with out.

a = 2
print(a)
2
2

Code with errors

If code contains errors, it will still be run and the exception shown as part of the output:

for a in range(10)
    print(a)
  File "/tmp/ipykernel_727/3806628970.py", line 1
    for a in range(10)
                      ^
SyntaxError: invalid syntax

Opening files

The working directory is the same as the .do.txt file. You may want to use os.chdir to change the directory.

with open("../LICENSE") as f:
    print(f.read())
Copyright (c) 2007-2015, Hans Petter Langtangen <hpl@simula.no> and
Simula Resarch Laboratory.

All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.

    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the
      distribution.

    * Neither the name of Simula Research Laboratory nor the names of
      its contributors may be used to endorse or promote products
      derived from this software without specific prior written
      permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Remarks:

The figure and movie files in doc/manual/* were made by the Doconce
author and is released under the same conditions as Doconce.