Coloring Python Syntax Inside a Label automatically. (pygments package)


For training purposes, we would like to color python syntax inside a label. The pygments python package would work the best for me.

What are some best methods to import this package into ignition? (Linux and Windows)

Below is an example on how to use the pygments package.

# Import packages!
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter

# Lets get our python lexer.
lexer = get_lexer_by_name("python", stripall=True)
# Lets setup our Html Formatter.
formatter = HtmlFormatter(linenos=False, noclasses=True, nobackground=True)

# We can read code from any source (file or query...ect.).
code = 'print \'this is a test\''
# Format the python code for HTML
result = highlight(code, lexer, formatter)
# Copy and paste into Ignition Label

RESULT (Can be copied and pasted into an ignition object to color syntax)

<HTML><div class="highlight"><pre style="line-height: 125%"><span></span><span style="color: #008000; font-weight: bold">print</span> <span style="color: #BA2121">&#39;this is a test&#39;</span>

After a brief look in its source, I didn’t see any obvious gotchas. Try placing its code in your ignition install’s pylib folder and restart the service. Then try to import it in a console. If it uses anything specfic to python 2.7, you’ll have to wait for Ignition v8.

Thanks for the help! The windows directory is easy to find but I want to make sure it is pointing at /var/lib/ignition/user-lib/pylib. Like these two directories are equal?

C:\Program Files\Inductive Automation\Ignition\user-lib\pylib

Yes, that’s the right location in either case. (It can be different on linux, too, if someone does a manual install from the zip file.)

1 Like