Sunteți pe pagina 1din 37

Python-Programming in

for beginner's

Structure of the book


The following documentation will give basic understanding of the below topics. After
going through this one can be able to script small programs using python. Which also gives a
basic understanding how Katana works inside and will be able to automate Katana as per

Understanding scripting


Understanding Katana

Katana Scripting


Knowledge of Katana to understand scripting for Katana

Programming and Scripting

Scripting languages are languages that don't require an explicit compilation step. For
example, you have to compile a C program before you can run it. But in the normal case, you
don't have to compile a JavaScript program before you run it. So JavaScript is sometimes
called a "scripting" language.

Some examples of "scripting" languages (languages that are traditionally used without
an explicit compilation step):

And examples which traditionally used with an explicit compilation step:


Few advantages of Scripting/ programming

creating new tools
extending the capability of a software

Different programming Types

Procedural programming: is a programming paradigm, derived from structured

programming, based upon the concept of the procedure call. Procedures, also known as
routines, subroutines, methods or functions, simply contain a series of computational steps to
be carried out.

Object-oriented programming (OOP): is a programming paradigm based on the concept of

"objects", which are data structures that contain data, in the form of fields, often known as
attributes, and code, in the form methods. object-oriented programming that uses classes is
sometimes called class-based programming.

Few features of OOPs

Overview of OOPs Terminology
Class: A user-defined prototype for an object that defines a set of attributes that
characterize any object of the class. The attributes and methods, accessed via dot
Class variable: A variable that is shared by all instances of a class. Class variables are
defined within a class but outside any of the class's methods.
Data member: A class variable or instance variable that holds data associated with a
class and its objects.
Function overloading: The assignment of more than one behavior to a particular
function. The operation performed varies by the types of objects (arguments) involved.
Instance variable: A variable that is defined inside a method and belongs only to the
current instance of a class.
Inheritance : The transfer of the characteristics of a class to other classes that are
derived from it.
Instance: An individual object of a certain class. An object obj that belongs to a class
Circle, for example, is an instance of the class Circle.
Instantiation : The creation of an instance of a class.
Object : An object is instance of a data structure that's defined by its class. An object
has data members and methods.

Python can do almost all types of things except creating OS. For python we can use
words - scripting and programming interchangeably. Python runs through interpreter and also
can be compiled and used. Python supports multiple programming paradigms, including
object-oriented, imperative and functional programming or procedural styles. It features a
dynamic type system and automatic memory management and has a large and
comprehensive standard library

Python is used in various developments.

GIS Programmings
Web developments
Desktop applications
Network programming
In VFX it can be used for Pipeline development as well as it can be used in
Maya/Katana/Nuke etc.

About python

Python is an interpreted programming language .Also it is open source software,

making it freely usable and distributable, version 3.4.3 is the latest version available and
freely downloadable through .

Most current Linux distributions and Macs are still using 2.x as default. Also most of
the VFX Houses use 2.x, so we are going to concentrate in 2.x. There is a syntax differences
in 2.x and 3.x.

Why Python

Python is a high-level, interpreted, interactive and object-oriented scripting language.

Python was designed to be highly readable which uses English keywords frequently where
as other languages use punctuation and it has fewer syntactical constructions than other
Python is Interpreted: This means that it is processed at run time by the interpreter and
we do not need to compile our program before executing it. This is similar to PERL
and PHP.
Python is Interactive: This means that you can actually us Python prompt and interact
with the interpreter using python statements directly to write your programs.
Python is Object-Oriented: This means that Python supports Object-Oriented style or
technique of programming which allows to use OOPs concepts like encapsulation,
inheritance etc.
Python is Beginner's Language: Python is a great language for the beginner
programmers and with easy syntax, and also supports the development of a wide
range of applications
We have IDLE ((Integrated DeveLopment Environment ) to write scripts. We can also
use any text editor to write python scripts.

Few definitions related to python

Pyside: Python bindings for QT (similar to pyqt4)

Pymel: Python binding for MEL
Modules: A module is a python file that generally has only definitions of variables,
functions, and classes. Modules in Python are simply Python files with the .py
Functions: Functions are programs that perform a specific task, which you can incorporate
into your own, larger programs. After you have created a function, you can use
it at any time, in any place.
Packages: A package is a set of modules or sub-packages. A package is actually a
directory containing either .py files or sub-directories defining other packages.
When loading a package, the file is executed
Getting into Python

Download and install python. By default python is installed in linux distributions. Get
into shell and type python to start python directly in shell.

[abc@localhost]# python

Here we can find which version of python we are using on which version GCC. To get
out of python use command exit()


Syntax of python

Identifier is the name given to entities like class, functions, variables etc. in Python. It
helps differentiating one entity from another. Python is a case sensitive programming
language. Thus, name and Name are two different identifiers in Python.
Here are following naming convention for Python:
Class names start with an uppercase letter and all other identifiers with a lowercase
Starting an identifier with a single leading underscore indicates by convention that the
identifier is private.
Reserved words
The following list shows the reserved words in Python. These reserved words may not
be used as constant or variable or any other identifier names. All the Python keywords
contain lowercase letters only.
and exec not
assert finally or
break for pass
class from print
continue global raise
def if return
del import try
elif in while
else is with
except lambda yield

Lines and Indentation:

There are no braces to indicate blocks of code for class and function definitions or flow
control. Blocks of code are denoted by line indentation, which is important to keep in mind.
The number of spaces in the indentation is variable, but all statements within the block must
be indented the same amount. In the below example the indentation is different for If and else
, this is wrong in python
if True:
print "True"
print "False"

Multi-Line Statements:
Statements in python are usually one liners. Python allows the use of the line
continuation character (\) to denote that the line should continue. For example:

>>> total = 5+ \
6 + \

Quotation in Python:
Python accepts single ('), double (") and triple (''' or """) quotes to denote strings , as
long as the same type of quotes ends the string. In the below example all are correct.
>>> a = 'hi'
>>> a= hi
>>> a= ''' hi'''
Comments in Python:
A hash sign (#) begins a comment. All characters after the # and up to the physical line
end are part of the comment and the Python interpreter ignores them.

Multiple Statements on a Single Line:

The semicolon ( ; ) allows multiple statements. Here is a sample snip using the
>>>import sys; x = 'foo'; sys.stdout.write(x + '\n')

Writing Python scripts

Lets get into command line python / Interactive mode, where we can directly type
python statements/ commands. To print anything use print command with quotes. You can
see both types of quotes are working.

We can do all mathematical operations directly in python console interactively.

Data types in Python:
Numbers : Python supports different numerical types:
int (signed integers)
long (long integers [can also be represented in octal and hexadecimal])
float (floating point real values)
complex (complex numbers)
String : Strings in Python are identified as a set of characters in between quotations.
List : Lists are Python's compound data types. A list contains items separated by
commas and enclosed within square brackets ([]). To some extent, lists are similar to
arrays in C. One difference between them is that all the items belonging to a list can
be of different data type. The values stored in a list can be accessed using the slice
operator ( [ ] and [ : ] ) with indexe starting at 0.
Tuple : A tuple is another data type that is similar to the list. A tuple consists of a
number of values separated by commas. The main differences between lists and
tuples are: Lists are enclosed in brackets ( [ ] ) and their elements and size can be
changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated.
Tuples can be thought of as read-only lists.
Dictionary : can store any number of Python objects, including other container types.
Dictionaries consist of pairs (called items) of keys and their corresponding values.

>>>dict = { 'abc': 123, 'bb': 37 };

Along with the command line statements we can save .py file and run it through
command line. Different commands / statements can be combined in a python file and which
can be executed using 'python' command in shell.

[abc@localhost]# python

Now lets write a script which takes input from user and does some mathematical
calculations. The script ask user to input radius of sphere and it calculates circumference and
prints it.
There are several types of operators available in scripting and programming language.
Lets look at operators can be used in python-programming.

Mathematical operators

+ Addition
- Subtraction
* Multiplication
/ Division
% Reminder
** exponent 10**20 is 10 to the power 20
// floor division 9//2 is equal to 4

Comparison operators

== equal
!= not equal
<> not equal
> greater than
< less than
>= greater than or equal
<= less than or equal

Assignment operators

= equal
+= c +=a is equivalent to c = c+a
-= c-=a is equivalent to c=c-a
*= c =a is equivalent to c= c*a
/= c/=a is equivalent to c =c/a
%= c%=a is equivalent to c=c%a
**= c**=a is equivalent to c=c**a
//= c//=a is equivalent to c=c//a

Logical operators

and (a and b) is true

or (a or b) is true
not not (a )

Membership operators

in x in y, result is 1 if x is a member of y
not in x not in y, results 1 if x is not a member of y
Decision Making

if statements:An if statement consists of a expression followed by one or more

if...else : An if statement can be followed by an optional else statement, which executes
when the boolean expression is false.
nested if: You can use one if or else if statement inside another if or else if statement(s).

# syntax for input and operator if, elseif and else

x = int(input("Please enter an integer: "))

if x < 0:
x = 0
print 'Negative changed to zero'
elif x == 0:
print 'Zero'
elif x == 1:
print 'Single'
print 'More'


while loop: Repeats a statement or group of statements while a given condition is true. It
tests the condition before executing the loop body.

# the sum of two elements defines the next

a, b = 0, 1
while b < 200:
print b,
b = a+b

for loop: Executes a sequence of statements multiple times and abbreviates the code
that manages the loop variable.

Nested loops:You can use one or more loop inside any another while, for or do..while loop.

Break: Terminates the loop statement

Continue: Causes the loop to skip the remainder of its body and immediately retest its
condition before to reiterating.

Pass: The pass statement in Python is used when a statement is required

but you do not want any command to execute.
# using loops and break operator

for n in range(2, 1000):

for x in range(2, n):
if n % x == 0:
print n, 'equals', x, '*', n/x
# loop fell through without finding a factor
print n, 'is a prime number'

You can define functions to create the required functionality. Here are few
rules to define a function in Python.
Function blocks begin with the keyword def followed by the function name and
parentheses ( ( ) ).
Any input parameters or arguments should be placed within these parentheses. we
can also define parameters inside these parentheses.
The code in every function starts with a colon (:) and is indented.
IT returns value [expression] .

#syntax of a function
def functionname( parameters ):
return [expression]

Global vs. Local variables:

Variables that are defined inside a function body are local, and those defined outside
are global variables. Global variables can be used in other functions as well. Writing a
function for equiation wtith arguments
#Writing a sample function
def myfunc(n):
a, b = 0, 1
while b < n:
print b,
a, b = b, a+b

# Now call the function we just defined:

A module is an organised Python code. Adding related code into a module makes the
code easier to understand and use. Simply, a module is a file consisting of Python code. A
module can define functions, classes and variables. A module can also include runnable

The from...import Statement

Python's from statement lets us import specific attributes from a module into the current
scripts The from...import has the following syntax:
from modulename import name

We can use 'import' in python to import different modules.

Examples :
from Katana import Nodes3DAPI

from PyQT4 import UI4

Syntax of module

# Define variables:
one = 1
pi = 3.14

# defining functions
def printhello():
print "hello"

def circumf(input):
print input * 2*pi

# define a class
class mytest:
def __init__(self): = input("Name class? ")
self.num = input("number of students")
self.section = input("section of class")

def printdetails(self):
print "name of class is " +
print self.section, "has, " + self.num +of students
once we have run the above module it created .pyc file. Now in the folder we can see and firstmodule.pyc.

.pyc contain the compiled bytecode of Python source files. The Python interpreter
loads .pyc files before .py files, so if they're present, it can save some time by not having to
re-compile the Python source code

Locating Modules:
When we import a module, the Python interpreter searches for the module in the
following sequences. One can write own python modules and keep at PYTHONPATH
location and use import to use the functions and classes
The current directory.
If the module isn't found, Python then searches each directory in the shell variable
Both fails, Python checks the default path which is /usr/local/lib/python/. In linux

The PYTHONPATH is an environment variable, which has list of directories.

We can set the path location using the below statement in windows using environment
we can set location in linux using the below statement in shell/bash
set PYTHONPATH=/usr/local/lib/python
File I/O in Python

Using python we can create and edit the text data in any file. For example we can
store the any specific connections data of a maya scene file to a text file and it can be reused
in another file.

Opening A File
To open a file, we use the open() function to create a file object. Open takes two
arguments: the name of the file and the mode for which we'd like to open the file.

A file can be opened for reading ("r") or writing ("w"), just as with most other languages.

filename = myfile.txt
file = open(filename,'r')

Reading From A File

Read the file and print it using the below code

content =
print content

print line by line

lines = file.readlines()
for line in lines:
print line

Closing The File

We can close the file using close() function.


writing the text to a file

filename = 'myfile.txt'
file = open(filename, 'w')
file.write(hi this is my file)

Appending To An Existing File

We can append file using 'a' instead of write

file = open(filename, 'a')

file.write(' this is appending text')
OOPs concepts in Python

Class are blueprint of the programme. It describes how to make something. You can
create lots of objects in class. And there can be lots of classes in a programme. We can
create classes using 'class' . Below is the syntax of a class
# Defining a class
class myclass:
[statement 1]
[statement 2]
[statement 3]

Another example of class

#An example of a class

class Shape:
def __init__(self,x,y):
self.x = x
self.y = y

def area(self):
return self.x * self.y
def perimeter(self):
return 2 * self.x + 2 * self.y
def scaleSize(self,scale):
self.x = self.x * scale

The first method __init__() is a special method, which is called class constructor or
initialization method that Python calls when you create a new instance of this class.
We can use inheritance to inherit one class from another.

We can write several programs using python. Below are the few examples which we
can try to write using different modules available online, which we can download and use.

Examples scripts can be written :

Small raytracer using python
Autmating Maya/ Katana/ Nuke
Android game using python
Download youtube files from internet
Automating facebook and linkdin responses

By now we understood the basics of python and its uses. Lets understand Katana

Katana is a 3D appliction designed for lookdev and lighting. Katana mainly consists of

SceneGraph: A data tree containing all the information needed to render a scene.All data of
the scene graph is stored in Attributes. Scenegraphs heirarchical structure is made up of
locations that can be referenced by their path.

NodeGraph: A recepie in katana is an arrangement of instructions int the form of connected

nodes to manipulate 3d scene. Katana constructs a scene graph of scene data from the
content of the NodeGraph.and the SceneGraph data is sent to renderer to render it.

Before going deep into Katana scripting lets understand Groups/Macros/Supertools

Group : Group nodes are nodes that can contain a number of child nodes. They are used to
simplify the nodegraph by collecting nodes.
Group node can be created by selecting on or more nodes and pressing Ctrl+G

Macros: Macros are nodes that can contain a number of child nodes, and publish them so
that they can be saved and recalled in other projects.

SuperTools: Super tools are compound nodes where the internal structure of nodes is
dynamically created using python scripting. Internal nodes can be created and deleted using
user actions.

Creating a Macro:

Lets create a sample macro step by step, which prunes object based on location in
scenegraph. This macro will prune lights having name ML0 and ML1 internally, and shows
the parameter which are exposed to user.

Create prune node and a switch which will prune *ML0* location from scene graph.
Similarly create another prune node and a switch which will prune *ML1* location from
scene graph
We can create as many as prune nodes and switches based on our requirement
Now we need to create a group out of these 4 nodes

Use ctrl+ Middle click to go inside the group node and using python scripting we
create input and output port for the node Group.

test = NodegraphAPI.GetNode('Group')
We can see if the switch value is 1 then the location is not pruned and if it is 0 then
location is pruned

Now expose the parameters to the group

Use Alt+E to go to the parameters tab of Group node.
Use edit node button to add user parameters tab.
Now click add to add new parameters
Rename the parameters name to ML0 and ML1
Now select Widget Type -> Boolean to set the type of the parameter to boolean
now using Shift select both merge node parameters along with group parameters

Copy parameter from 'ML0', and paste expression to 'ML0Switch' parameter of Group
Copy parameter from 'ML1', and paste expression to 'ML1Switch' parameter of Group

This will set link between the two values and if we edit the parameter from Group node
then the value of the merge node will change automatically.
To change group node appearance we can use
Editnode -> Toggle Group node Appearance
Now go to Group node and click ' Finish editing user parameters' to finish the editing
Now you can set the parameters to yes / no to prune the location
Once everything is done we can publish the 'Group' node using editNode-> save as
Macro and give the name prune.macro
Now we can use prune_User macro in any project/ scene

We can also create this macro through nodeGraph -> New->macro->_User-


We can re-edit the macro if required and republish it with the same name prune.macro
and can be used again

Once the macro is published it can be used in different scenes and recipes as per our
Now lets jump into scripting in Katana
Katana Scripting

Now we can work with python to create and edit nodes in katana. Use python tab in
katana to write scripts.

Attribute types in Katana:


We have noticed that while we can manually edit parameters on nodes in Nodegraph,
we cont edit attributes on scene graph location, this is because the flow of information from
Nodegraph to Scenegraph is strictly one way. This an important concept to keep mind when
writing attribute script nodes.

The following code shows how to get the full list of all the available node types using
the GetNodeTypes method in the NodegraphAPI module:

nodetypes = NodegraphAPI.GetNodeTypes()
for nodetype in nodetypes:
print nodetype
NodegraphAPI : The Nodegraph API is a Python interface for creating Katana recipes by
adding and connecting nodes, and setting Parameters. The Nodegraph API
cannot access the Scene Graph . The Node Graph API can be accessed by Python scripts in
the Python tab, Super Tools, plug-ins, shelves and other custom UI.

Getting help of different modules

To get help on package NodegraphAPI, use command help, we can use help to
know about the nodes, APIs etc


Similarly help can be used for other node types aswell. In UI4 we have other
classes/packages called Util.

Try out help on other nodes as well. Also print can be used to print to know about the


# to get the help on classGroupStackNode in module


Creating a new Node:

As we know we need to create a node at root, we need to get the root and then create
any node. The below script will create GroupStack node and Rename the node.
mynode = NodegraphAPI.CreateNode('GroupStack',root)

#get the help on mynode and find out its attributes


#rename the node


Now lets create a prman object settings node, rename it and stack it in mystack node

#create node
myprman = NodegraphAPI.CreateNode('PrmanObjectSettings', root)

#rename node

#put node in groupstack


#check the child nodes available

Adjusting the attributes using scripts

We can adjust the attributes of any node through script. We need to enable the local
assignment and we can set the value of any attribute. The below script will create a
prmanGlobalSettings node and set the pixelVariance value.

root = NodegraphAPI.GetRootNode()
myprman = NodegraphAPI.CreateNode('PrmanGlobalSettings', root)

en = myprman.getParameter

#enable assignment to True


#set pixelVariance value to 2 at frame 0

val = myprman.getParameter

If we already have the node PrmanGlobalSettings then we can use the below script to
select the node (using GetNode) and the other script remains same
#get the node wiht name 'PrmanGlobalSettings' and store it in
myprman to edit its values
myprman = NodegrapAPI.GetNode('PrmanGlobalSettings')

#editing of the value is same as above script

Selecting nodes:

Select nodes and run the below script to get selected nodes.

sel = NodegraphAPI.GetAllSelectedNodes()
print sel

Create a prman global settings node and use the below script to get child parameters
of the node

sel = NodegraphAPI.GetNode('PrmanGlobalSettings')
for p in sel.getParameters().getChildren():
print p

Delete nodes

sel = NodegraphAPI.GetNode('PrmanGlobalSettings')

Delete selected nodes through script, select the nodes and save in list, to get the
items from list and delete use for loop

sel = NodegraphAPI.GetAllSelectedNodes()
for i in sel:

Get list of selected locations

list = ScenegraphManager.getActiveScenegraph().getSeletedLocations()
print list


Another concept which we need to understand before writing scripts is Producer. As

we already discussed about the sceneGraph, it only shows locations currently expanded in
the scenegraph tab. SceneGraph changes with the current viewed node in NodeGraph.
Scenegraph gives different locations with different nodes selected in nodeGraph. To get
appropriate scene data at a given node we can use Producer. Using a Producer is the correct
way to iterate the Scenegraph if you ever need to. Its available through the Nodes3DAPI.

In any scene we can getnode which is in the end of a nodegraph and use producer to
get the accurate scene graph at that node. Below is the script to select objects through CEL
statement using python. Create a collection named bone to get the CEL command working
for the below script.

mynode = NodegraphAPI.GetNode('PrmanGlobalSettings')
prodcuer = Nodes3DAPI.GetGeometryProducer(mynode, 0)
cel = GeoAPI.Util.CollectPathsFromCELStatement(producer,

sg = ScenegraphManager.getActiveScenegraph()
Example Script

Lets create a script which creates an prmanObjectSettings node and add the selected
objects from the scene graph. In UI we can define the name of the node . Along with this we
can set the attributes of the PrmanObjectSettings. For now if the node exists then it replaces
the selected objects

class Example(QtGui.QDialog):

def __init__(self, parent =

super(Example, self).__init__(parent)

#########UI Design###########

layout = QtGui.QGridLayout()
label = QtGui.QLabel("name",self)
self._labelInput = QtGui.QLineEdit(self)
indow","",None, QtGui.QApplication.UnicodeUTF8))

createButton = QtGui.QPushButton("create",self)
layout.addWidget(createButton , 3, 0, 1, 2)
createButton.move(30, 200)

qbtn = QtGui.QPushButton('Quit', self)

qbtn.move(120, 200)
layout.addWidget(qbtn, 4,0,1,2)

self.setGeometry(500, 300, 350, 350)

def prmanobj (self):

name = str(self._labelInput.text())

selected =
root = NodegraphAPI.GetRootNode()
if NodegraphAPI.GetNode(name):
groupnode =
NodegraphAPI.CreateNode('PrmanObjectSettings', root)

sel = NodegraphAPI.GetNode(name)
selection = sel.getParameter('CEL')
selection.setValue('('+' '.join(selected)+')', 0)

window = Example()

Attribute Scripts:
Attribute scripts are similar to attribute modifiers, where we can modify the attributes
through python scripts. Through attribute script we can modify attribute at any given location.
We can create attribute scripts which run only on certain type of locations. AttributeSet will be
much faster than AttributeScript if all you're doing is setting attributes. AttributeScript can do a
lot more than set attributes.

Lets create an attributescript which changes the maxTimeSamples using python script.
MaxTimeSamples is an option which is not an object based setting, which is scene based or
layer based. So we need to apply the script at '/root' location. It wont work on any other
location or on object.

Create an AttributeScript node.

Set location to '/root'
Put the below script in script box in the node.


Similarly we can write different types of attribute scripts which can do lot of
manipulation in the scene/Nodegraph. We can set visibility setting using script which wont be

Lets write a small script which checks the shutterclose, if it is 1 then make
maxtimeSamples to 4, and if shutterclose isn't 1 then it sets maxTimeSamples to 1

motionblur = GetAttr('renderSettings.shutterClose')
if motionblur == [1]:
We can set anything based on conditions, Get the value of any attribute and based on
the value we can set any attributes value on the fly. Below examples can be created using
Disabling Deep AOVs using Attribute Script
Disable indirect specular
Disable material

Super tools are compound nodes where the internal structure of nodes is dynamically
created using python scripting. Internal nodes can be created and deleted using user actions.
Many of Katana's common user level nodes (such as Importomatic, Gaffer and
lookfileManager) are actually super tools.
We can Ctrl+middle click to see the internal structure of SuperTool

In general super tool consist of:

A python script written using Katana NodegraphAPI that declares how the super tool
creates its internal structure.
A python script using PyQt that declares how the super tool creates its UI in the
Parameters tab
Another python script for common shared utility functions needed by the both the
nodes and UI scripts
Plugin registry is required to use super tool, which can be performed through

Other APIs available in katana:

Viewer manipulaterAPI

Few Major changes in Katana 2

There are several enhancements and changes are being made in Katana2.x
compared to Katana 1.x. Lets have a look of few major changes.

Gaffer3 : New gaffer node is introduced in Katana2.x, has been created to provide improved
performance when dealing with large number of lights in the scene.

Lua OpScripts: Katana 2.x introduces a Lua based Opscript node which can be used
instead of python based AttributeScript nodes. It is recommended to use OpScript where
ever possible.
Keyboard Shortcut manager: A new module has been added to assign keyboard shortcuts
in Katana which was not available in the earlier versions.

Geolib3 : It is Katana's new scene graph processing library. It works at Katana's core to
support large data sets. In the earlier versions Geolib2 reconstructed the whole scene graph
on every edit, Where as Geolib3 allows inter-cook scene data re-use.

Python Tab: Tab has been enhanced for user friendly usage.

Katana references
There are very few resources available on katana and its scripting.

Katana documentation

Python Reference:
There is a huge list of resources available online for Python. Advanced python-
programming can be learned through internet.

Please write your suggestions and comments to Email: