Print

Using Python in Stackbuilder

Please ensure that you have reviewed Creating custom software blocks before beginning this article.

Basic Python programming in Interstacks


An example of custom software blocks containing Python code

Interstacks software blocks are made using the Python scripting language. We will make no attempt here to be a Python programming manual. In this article, we will show some basic Python scripting for Interstacks with emphasis on classes and usage that are unique to Interstacks. We also include a brief survey of Python, intended to serve as a quick reference.

Every Interstacks block has input terminals that receive messages and output terminals that send messages. When you make a new software block you can add multiple Input Handlers for input terminals, multiple output terminals, a single Startup Handler, and an Interval Handler. The Startup Handler runs once, before any other handlers, when the block receives its first message. The message received by an input terminal’s message handler is in the variable “message”.

Send Message: Send a message out of an output terminal by using I.sendmessage

I.sendmessage(2, ‘hello world’) # sends the message ‘hello world’ out of terminal 2
I.sendmessage(4, mylist[3]) # sends the fourth entry of the list “mylist” out of terminal 4

I.debug: Using I.debug will display its arguments on the console trace. This is useful for testing your software block.

I.debug(“Put this on the console trace”, mylist[3])

Get Next Message: If you need to receive an input message from an input terminal that is different from the input handler you are scripting, you can use the I.getnextmessage function to return a tuple with (terminal, value)

getnextval = I.getnextmessage((4,), wait=1) # returns tuple with (terminal,value)
myval = getnextval[1] # we just want the value

The above example gets the value received by input terminal 4. It will wait until it receives that message. Alternatively, you can provide a timeout value that will cause the function to return if that time is exceeded without receiving a message.

getnextval = I.getnextmessage((4,), wait=1, timeout = 0.5) # returns tuple with (terminal,value)
myval = getnextval[1] # we just want the value

In the above example, the timeout value is in seconds. I.getnextmessage is often used to provide a transactional, or synchronizing mechanism to a data flow.

Base – Stack Ready: Sometimes a message flow needs to be kick started when the stack is powered up. There is an output terminal on the Base hardware block called “Stack Ready”. It sends a message one time, as soon as the stack is powered up and running.

Indentation Syntax: Python does not require the type (e.g. integer, character, string, list) of a variable to be declared. It also has minimal syntax requirements. Its primary one is that control blocks are defined by white space i.e. indentation.

If – Else If – Else

Example 1:

# This is a Python message handler
#
x = message
if x == '1':
I.sendmessage(2,'hello world')

Example 2:

# This is a Python message handler
# Lights Control Block
# Input Color
x = message
I.debug('gk test print', x) # FOR TEST ONLY. print to console trace
if x == '6':
I.sendmessage(2, 'rrrrrrrrrrrr')
elif x == '2':
I.sendmessage(2, 'gggggggggggg')
elif x == '3':
I.sendmessage(2, 'bbbbbbbbbbbb')
elif x == '4':
I.sendmessage(2,'cccccccccccc')

In the above examples, the input message is assigned to the variable “x”. “x” is then compared to various values in sequence. If x is equal to the character ‘6’ then send the message out of terminal 2, else if x is equal to the character ‘2’ then send a different message out of terminal 2.

Other comparison operators include:

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

Boolean operations include:

  • or
  • and
  • not

Example:

if foo != 7 and bar < 10:
I.sendmessage(4, ‘All is well’)

Loops: while loops are a general looping tool, break jumps out of closest enclosing loop, and continue jumps to the top of the closest enclosing loop.

while True:
reply = getinput('enter')
if reply == 'stop' : break
I.debug(‘send to console trace’, reply)
Else:
I.sendmessage(3, 42)

Global Variables and Functions: Variables that you want to be shared across handlers within a software block are called global variables. They are typically declared and initialized in the startup handler by saying:

G.foo = 0

or

G.foo = “hello world” or G.foo = [1,2,3]

The uppercase “G” followed by the “.” then the name is required. They can then be referenced in any handler by just using G.foo

To declare functions that you want to use across handlers within a software block, do the following in the startup handler:

@gdef
def myf/spaceunc() :
x = 7
I.sendmessage(4, ‘Good job’)

Then in any handler, you can use G.myfunc()

Note: the scope of the globals is within the software block only, not across all software blocks. If you want to share information across software blocks, send messages between them. If you want to share functions across software blocks, you must create a library and then add it to every software block that wants to use the functions. 

Lists: Ordered collections of other objects.

Example:

  • L = [1, 2, 3] L = [1, [2, ‘three’], 4] L = [123, ‘spam’, 1.23 ] L = [ ] len(L) returns length.
  • L + [4 , 5, 6] concatenation, doesn’t change the original list.
  • L.append(‘NI’) add object at end of list.
  • L.pop(2) or del L[2] deletes item.
  • L.insert L.remove L.sort() L.reverse()
  • valueread = [ UUID(‘~110044559988334422’), [‘value1’, 7], [‘value2’, 8] ]
  • theUUID = valueread[0]
  • firstName = valueread[1][0]
  • firstValue = valueread[1][1]

Strings

  • s = ‘spam’
  • len(s) returns length
  • s[0] s[1] s[-1] would be m. s[1:3] is pa
  • s + ‘xyz’ concatenates. s *4 repeats 4 times into 4x bigger string.
  • s.find(‘pa’) returns offset.
  • s.replace(‘pa’, ‘xyz’) returns replace result, doesn’t change s.
  • line = ‘aaa,bob,ccc,ddd’
  • line.split(‘,’) split on delimiter and return list of strings. […..] n t ord(‘n’) returns 10.
  • Strings are immutable, so can’t do s[0] = ‘z’. need to do s = ‘z’ + s[1:]
In This Article