Python code embedded

This tutorial explains how to embed Python code from a script, located in certain directory.

Highlight the file

Approach demonstrates that highlight shortcode can be combined with readfile shortcode. File can be located in any directory, full path (starting from repo directory) should be specified.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import sys
import numpy


class Base:
    """
    Base class
    """
    def __init__(self):
        self.x = None
        self.y = numpy.sin(numpy.pi/2.0)

    def value(self):
        return self.y


def say_hello():
    """
    Prints 'Hello World' message
    """
    b = Base()
    print("Hello World", b.value())


if __name__ == '__main__':
    say_hello()

Highlight the file with custom shortcode: highlightfile.

Shortcode provides link to the file for download.

File is located in static directory, full path should be specified.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import sys
import numpy


class Base:
    """
    Base class
    """
    def __init__(self):
        self.x = None
        self.y = numpy.sin(numpy.pi/2.0)

    def value(self):
        return self.y


def say_hello():
    """
    Prints 'Hello World' message
    """
    b = Base()
    print("Hello World", b.value())


if __name__ == '__main__':
    say_hello()

code_snippet.py

File is located in same directory. No path is required.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
    int min3(int a, int b, int c) {
       if (a < min(b,c)) {
          return a;
       }
       else if(b < min(a,c)) {
          return b;
       }
       else if(c < min(a,b)) {
          return c;
       }
    }
    int min4(int a, int b, int c, int d) {
       if (a < min3(b,c,d)) {
          return a;
       }
       else if(b < min3(a,c,d)) {
          return b;
       }
       else if(c < min3(a,b,d)) {
          return c;
       }
       else if(d < min3(a,b,c)) {
          return d;
       }
    }
    

another_code_snippet.py

Highlight the file and mark certain line numbers.

Same as in the example above with additional highlighting of selected lines.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
    int min3(int a, int b, int c) {
       if (a < min(b,c)) {
          return a;
       }
       else if(b < min(a,c)) {
          return b;
       }
       else if(c < min(a,b)) {
          return c;
       }
    }
    int min4(int a, int b, int c, int d) {
       if (a < min3(b,c,d)) {
          return a;
       }
       else if(b < min3(a,c,d)) {
          return b;
       }
       else if(c < min3(a,b,d)) {
          return c;
       }
       else if(d < min3(a,b,c)) {
          return d;
       }
    }
    

another_code_snippet.py