Python API tutorial 2: writing your first API script¶
Let's write a very simple script that opens an Understand project and prints the full path of every file in it.
The script¶
Save this as sample.py:
import understand
db = understand.open("C:/projects/test.und")
for file in db.ents("file"):
print(file.longname())
Run it with the bundled interpreter:
upython sample.py
Line by line¶
import understand — put this at the top of every script that uses the API. It loads the
understand module.
db = understand.open("C:/projects/test.und") — opens the project and returns a
Db object. db
holds everything the script can query. Every project path ends in .und. Open one project per script
before you query anything.
for file in db.ents("file"): — ents is short for entities; each one is an
Ent object. Calling db.ents("file") asks for
every entity in the project and keeps only the ones whose kind matches the filter string "file".
You'll learn much more about entities and kind filters in the next tutorial.
print(file.longname()) — longname() returns the entity's fully qualified name; for a file
entity that's its full path.
Take the project path as an argument
Hard-coding the .und path is fine for a first script, but most real scripts read it from the
command line, e.g. db = understand.open(sys.argv[1]), so the same script works on any project.
Next¶
You've opened a project and listed its files. Next you'll learn what entities and references really are, and how kind filters select exactly the ones you want.
← Tutorial 1: getting started · → Tutorial 3: entities, references, and filters