Using python to call different code blocks in babel
This entry has two main ways to call different code blocks from babel. The first example is based on an example from Eric Shulte org-scraps using session
header argument and the second is based on a noweb
example that I found here. Also, the last example shows how to call a named code block using #+CALL
.
Persistent python
Import modules from scikit-learn library using untitled session header argument. The example below shows the raw orgmode content.
Import modules.
#+begin_src python :session :results silent
from sklearn import svm
from sklearn import datasets
#+end_src
#+RESULTS:
Write a function definition.
#+begin_src python :session :results silent
def svm_call(x, y):
clf = svm.SVC()
return clf.fit(x, y)
#+end_src
Call function definition & imported modules.
#+begin_src python :session :results output
iris = datasets.load_iris()
x, y = iris.data, iris.target
svm_call(x, y)
#+end_src
#+RESULTS:
:
: >>> SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,
: decision_function_shape='ovr', degree=3, gamma='auto', kernel='rbf',
: max_iter=-1, probability=False, random_state=None, shrinking=True,
: tol=0.001, verbose=False)
Noweb
Basic noweb example. Use the <<name-of-block>>
to call another code block.
#+NAME: init_block
#+BEGIN_SRC python
constant=19
def some_function(x):
return constant * x
#+END_SRC
#+BEGIN_SRC python :noweb yes
<<init_block>>
return some_function(13)
#+END_SRC
High-level structure of a file using noweb
This is based on noweb, and particularly in an example by Eric H. Neilsen, Jr.
To create (tangle) the dog_module.py
file use C-c C-v t
.
Main structure of python file
#+BEGIN_SRC python :noweb yes :tangle dog_module.py :exports none
"""This is a class definition example document"""
# imports
import sys
<<dog-main-imports>>
# constants
# exception classes
# interface functions
# classes
<<dog-defn>>
# internal functions & classes
<<dog-main>>
# run standalone
if __name__ == '__main__':
status = main()
sys.exit(status)
#+END_SRC
Import argparse
module
#+NAME: dog-main-imports
#+BEGIN_SRC python
from argparse import ArgumentParser
#+END_SRC
Import the class definition Dog
#+NAME: dog-defn
#+BEGIN_SRC python
class Dog:
kind = 'canine' # class variable shared by all instances
def __init__(self, name):
self.name = name # instance variable unique to each instance
self.tricks = [] # creates a new empty list for each dog
def add_trick(self, trick):
self.tricks.append(trick)
def print_attributes(self, name, tricks):
print("Name: {}".format(self.name))
print("Tricks: {}".format(self.tricks))
#+END_SRC
Import the main()
function.
#+NAME: dog-main
#+BEGIN_SRC python
def main():
parser = ArgumentParser(description="A class for dogs")
parser.add_argument("-n", "--name",
type=str,
default="Rocky",
help="Name of the dog")
parser.add_argument("-t", "--tricks",
type=str,
help="Dog's learned tricks")
args = parser.parse_args()
name = args.name
tricks = args.tricks
puppy = Dog(name)
puppy.add_trick(tricks)
puppy.print_attributes(name, tricks)
return 0
#+END_SRC
Run the script with arguments and redirect Standard Output (Channel 1) and Standard Error (Channel 2) to Channel 1.
python dog_module.py --n Jack --t roll 2>&1
true
Name: Jack Tricks: ['roll']
Using Python interpreter you can call the class as shown below:
>>> from dog_module import Dog
>>> a = Dog('Jack')
>>> b = Dog('Charlie')
>>> a.add_trick('roll over')
>>> a.add_trick('play dead')
>>> b.add_trick('roll over')
>>> a.print_attributes(a.name, a.tricks)
Name: Jack
Tricks: ['roll over', 'play dead']
>>> b.print_attributes(b.name, b.tricks)
Name: Charlie
Tricks: ['roll over']
Call lines in python
Example adopted from here.
#+name: doubler
#+begin_src python :var n=2
return n**n
#+end_src
#+call: doubler(n=3)
#+RESULTS:
: 27