If you read that last #QuickTip, you may have asked yourself “How would I expand Hscript global variables & expressions with Python?”. That is, can you use Python to expand a global variable like
$HIP or even and Hscript expression? In this #QuickTip you will learn how to expand Hscript global variables & expressions with Python.
Expand Global Variables
Again, our trusty
hou module has the function we need to accomplish this task. The
hou.expandString(str) function takes a String and returns the value at the current frame. So for example, if we were at frame 41, I would get 1.6666666666666667 as a string.
frameTime = hou.expandString('$t') print(frameTime) #'1.6666666666666667'
The other thing you can do is evaluate the global variable or expression at a given frame. This uses an alternate function called
hou.expandStringAtFrame(*args). For this function, you pass in the global variable or expression and the frame number.
# time marker at frame 41 tf = hou.expandStringAtFrame('$T', 51) print(tf) #2.0833333333333335 # time marker at frame 51 ct = hou.expandString('$T') print(ct) #2.0833333333333335
Expanding Hscript Expressions
The other thing you may want to do is evaluate an Hscript expression for a given parameter. If you use
hou.expandStringAtFrame(*args) to expand Hscript expressions, you will need to add backticks
` to the expression in addition to wrapping it all in quotes. It can get messy. The problem is this function returns the value of a non-animated text parameter. There is another function that works better for this situation and that is
This function will allow you to grab the value of an animated parameter. The other thing you can do is expand global variables just as you are able to do with
hou.expandString(str). In this example I have a simple
sin expression on the
ty paramerter. If I want to grab the value evaluated by the Hscript expression using Python, I would do the following:
ex = hou.hscriptExpression('ch("obj/sphere_object1/ty")') print(ex) # 0.866025403784
ExpandString vs HscriptExpression
So if you can use
hou.hscriptExpression(*args) to expand Hscript expressions as well as Hscript global variables, why use
hou.expandString(str)? What’s the difference? The latter,
hou.expandString(str), will expand the variables and concatenate any other strings you pass into the function. You can use this to create a path object. The former will error out if you pass in variables or strings that are unknown. If you are creating pipeline tools and scripts and need to access Hscript global variables and evaluate Hscript expressions, these several functions can come in handy.