Overview
The platform includes a unique set of features for Python integration:
- Multiple Python Versions: Support for different Python versions.
- In-Solution Designer Editing: Edit and test Python scripts within the Designer.
- Tag Direct Access: Python can access real-time tags, Historian tables, and all modules' namespaces.
- .NET Integration: Python can call methods in C# or VB.Net, and vice versa.
- Web Integration: Web pages can use Python classes from the server.
- Extensibility Toolkit: Allows external Python applications to interface with the platform's servers.
On this page:
Table of Contents | ||||
---|---|---|---|---|
|
Installation and Setup
The Python Shell integration requires Python releases 3.7 onwards and the installation of Python.NET.
Setup Steps:
1. Install Python and Python.NET in the machines where you run the application and on those using the Solution Designer.
2. Configure the Solution Settings to select the appropriate Python shell folder.
Each solution can specify its own Python interpreter, facilitating the development and maintenance of different solutions that may require different Python versions.
Expand | ||
---|---|---|
| ||
You can download Python here. Check the Use admin privileges checkbox, and select Customize installation. |
Easy Heading Macro | ||||||||||
---|---|---|---|---|---|---|---|---|---|---|
|
Info | ||
---|---|---|
| ||
Quick tutorial videos: Using Python with TK Data Access, Using Python with Script Task, Using Python with Code Behind |
Introduction
Our Python Integration opens a great way to extend your projects with Python. Vastly increase the power and reach of your existing Python code by easily integrating it with our software platform!
- Supports ANY version of Python (3.x and 2.x).
- Access the Python namespace from within our software platform Scripts, Tasks, and CodeBehind.
- Execute (call) your Python code from within your projects (even NumPy, Matplotlib, etc).
- Create Python code that can interact with your project.
Create a task that executes your external Python code and passes parameters both ways — everything without a single line of code in your project.
- Schedule your task to trigger at set times or execute it as a function of a trigger (e.g. Event-based triggers).
- Machine Learning and AI integration made easy.
Overview
The programming in many of your projects will consist of C# or VB.Net 100% managed code that is designed to run in the Microsoft .NET framework.
Our software platform now includes Python as a programming language you can use in Code Behind, Scripts, Tasks, and interactively via external Python code.
Python is an interpreted, high-level, general purpose language. It is a popular language for machine learning, which is useful for things like Predictive Maintenance algorithms.
Software platform can use any version of Python, 3.x or the older and past end-of-life 2.x.
Users can use Python in three different ways:
Executing Python code from Script-Tasks
Using the Script → Task for Python: Execute Python code (.py) and using the Script Task interface to set and get parameters (no code needed in the Studio side).
Using Python for .NET
Python for .NET enabled the Python namespace in both C# and VB.NET applications. Create .NET code using the Python namespace to interact with the Python objects.
Using the TK DataAccess Toolkit
We provide a toolkit in Python (TKDataAccess.py) which allows the Python code and application to interact with the Studio projects.
System Requirements
Python Interpreter
The first step to use Python programming is to include a link to the version of the Python interpreter you want to use for your project.
You can download Python here.
During the installation of the Python Engine, |
select the option to “Install for all users”. |
Now you need to add the interpreter to your project. Go to Info → Settings tab and search for the Python field. Click the "..." button, navigate to find the installed Python Engine, and select the python.exe file.
Python for .Net
Python for .NET is a package that gives Python programmers nearly seamless integration with the .NET Common Language Runtime (CLR) and provides a powerful application scripting tool for .NET developers.
Python for .NET allows Python code to interact with the CLR and may be used to embed Python into a .NET application. The installation files and documentation are available here.
Check to see whether your Python and Windows versions are 32-bit or 64-bit before you download Python for .NET. This is only required if you intend to use the Python namespace in Studio Scripts and Display CodeBehinds.
Creating Scripts in Python
To create scripts based on the Python programming language, go to Scripts → Tasks, select a new blank row, and double-click on the Code column. After clicking Code, a combo-box will appear. Select Python from the combobox.
Note |
---|
Once a new task is created, the language type cannot be altered through the Code column. |
After creating a new script task, you need to edit it in the CodeEditor tab.
The configurations settings are detailed below:
If You install Python under your local user, you may have issues when running the solution as a service, or when deploying the solution for production.
Once you've downloaded, open the command prompt as an ADMINISTRATOR and type “pip install pythonnet”. For this work, you'll need internet access. If internet is not available, download and install manually. Once Python.NET has been installed, you can start using Python in your solution.
|
Expand | ||||||
---|---|---|---|---|---|---|
| ||||||
Go to Solution / Settingsand locate the Python Interpreter box. Click the "..." button, navigate to find the installed Python Engine, and select the python.exe file.
|
Once you've installed Python, you can take a look at our Python demo with code examples.
→ Learn more at Python Example.
Using Python in the Solution
The Python Example illustrates how to use the Python and .NET languages for the Scripts.
This section presents a summary of that information, listing the modules in the solution where Python code can be used.
Scripts Tasks and Classes
- Scripts / Tasks: Event driven or periodical tasks, running on the server computer. They can be written in Python, C# or VB.NET.
- Scripts / Classes: library of methods and functions that can be used on both server and client machines. They can be written in Python, C# or VB.NET.
Displays CodeBehind and Graphical Elements
The Code Behind for the displays can be written in C#, VB.NET or JavaScript, not Python directly. But from the CodeBehind you can call tasks and methods, which can be written in Python.
Shell Integration
- Shell Integration: allows you to execute Python code from external files.
This integration allows you to execute Python code from external files. Just create a Script Task with the following code:
Code Block | ||||
---|---|---|---|---|
| ||||
# This code call the execution of the external file using Python Shell
# with the optional args defined in this initial section
#
# The macro _ExecutionPath_ is replaced by the path where the solution is set to execute
# Replace that macro by a specific path, or user other built-in macros as nedded
#
arg1 = @Tag.Tag1
arg2 = @Tag.Tag2
result = TK.ExecutePythonShell("_ExecutionPath_ExternalSum.py", [arg1, arg2])
@Tag.Result = result |
Tip | ||
---|---|---|
| ||
Any Python scripts you create in Scripts / Tasks can be edited and tested in Scripts / Code Editor. To test your script, click on [Monitor Icon] in the top toolbar. This will run your code and display messages in the Output Window, under the script editor. This integration will work if your Python version is 3.7 or newer, with Python.NET installed, and the executable is correctly mapped in Solution / Settings. |
Designer Python Code Editor
Code Editor User Interface
The code editor can be accessed through Scripts / Code Editor.
Testing the code
When the editor is used to edit Script Tasks, you can test the scripts directly, using the Play button at the Task name line. The results of your code will show in the standard Designer output.
Accessing Tags and Modules Properties
The access to tags and other properties for other models is exactly the same as C# or VB.NET; just use the '@' symbol to access the properties directly, as shown in the image: '@Tag.Tag1'.
.NET Interoperability
Calling ScriptClass Methods
In the Script, or in any place in your solution where Expressions are allowed, you can use the following syntax to call classes.
Code Block | ||
---|---|---|
| ||
@Script.Class.TestClass.ExempleMethod(param1, param2) |
This activation is independent of the language the class was created in.
This means C# and VB.NET can call Python classes, and Python code can call .NET classes.
In this section:
- File Name: Name of .py file.
- Standard Output: Tag name that will receive all output printed via print.
- Arguments: List of arguments. This parameter list will be passed as arguments for the Python Engine (python.exe).
Warning |
---|
After making any changes, click the Apply Changes button. |
Using the Python Namespace in .NET
The Python namespace can be used in any script editor (Tasks, Classes, or CodeBehind) inside your project environment. To use the Python namespace, you simply need to install the Python.NET package, available on github.
The Python namespace provides several .Net methods that interact with Python codes and objects. See some of those methods below:
- Run a .py file using Python for .NET
Code Block |
---|
string ExecutePyFile(string pyFileName, Dictionary<string, object> locals = null, bool keepValuesAsPython = false)
string pyFileName = Python file
Dictionary<string, object> locals = Local variables inside Python code. Default is null.
bool keepValuesAsPython = Keep retuned values as Python objects or convert to .NET objects. Default is false.
string returns = If success return null else string contains error. |
- Run a Python code using Python for .NET
Code Block |
---|
string ExecuteCode(string code, string workingDirectory = null, Dictionary<string, object> locals = null, bool keepValuesAsPython = false)
string code = py file name
string workingDirectory = Working directory. It will be added in 'sys.path'
Dictionary<string, object> locals = Local variables inside Python code. Default is null.
bool keepValuesAsPython = Keep retuned values as Python objects or convert to .NET objects. Default is false.
string return = If success return null else string contains error. |
- Convert a Python value to a .NET value
Code Block |
---|
public static object FromPython(object value)
object value = Python value
object returns = NET value |
- Copy a Python object to a tag (Array or User Template)
Code Block |
---|
public static void CopyPythonObjectToTag(object source, string tagName)
object source = Python object.
string tagName = Tag Array or User Template. |
- Copy a tag (Array or User Template) to a Python object
Code Block |
---|
public static void CopyTagToPythonObject(string tagName, object target)
string tagName = Tag Array or User Template.
object target = Python object. |
- Create a Python object from a Python class
Code Block |
---|
public static object CreatePythonObjectFromPyFile(string pyFileName, string className, object[] parameters = null, string tagName = null)
string pyFileName = Python file name containg the definition of Python class.
string className = Python class name.
object[] parameters = Parameters for Python class while creating Python object.
string tagName = Tag name (Optional, Tag Array or User Template). If tag exists then copy all values to new Python object.
object returns = Reference to new Python object. |
- Get all attributes of a Python object
Code Block |
---|
public static IDictionary<string, object> GetAttributesPythonObject(object pythonObject, bool keepValuesAsPython = false)
object pythonObject = Python object/
bool keepValuesAsPython = Keep retuned values as Python objects or convert to .NET objects. Default is false.
IDictionary<string, object> = Dictionary contains attributes (name and value). |
- Set a new value for attributes of a Python object
Code Block |
---|
public static void SetAttributesPythonObject(object pythonObject, IDictionary<string, object> dic)
object pythonObject = Python object.
IDictionary<string, object> = Dictionary contains attributes (name and value) for setting. |
- Dump a python object to a string to send it to a TraceWindow
Code Block |
---|
public static string DumpPythonObjectToString(object pythonObject)
object pythonObject = Python object.
string returns = Dump information of object. |
Note |
---|
If you need to install other Python modules and libraries (such as numpy, pythonnet, matplotlib, etc.), you must install them in the same location as Python Engine (python.exe). |
Warning |
---|
All the methods listed above are disabled for Mono projects and HTML5 displays. |
TKDataAccess.py
You can create code in the Python environment and use the TKDataAccess.py file to interact with the projects.
Warning |
---|
Our software platform provides the TKDataAccess.py file. When you use it, you need to make sure it is installed in the same folder as our software. |
Below are some methods from TKDataAccess.py that you can use:
- Open a connection with the server
Code Block |
---|
Connect(runtimeHostAddress, userName, password):
runtimeHostAddress = IP address or server name
userName = User name.
password = Password |
- Get a server connection status
Code Block |
---|
GetConnectionStatus () |
- Check your script's connection to the server
Code Block |
---|
IsConnected () |
- Disconnect from Server
Code Block |
---|
Disconnect() |
- Set a flag waiting value from server
Code Block |
---|
SetSyncFlag(flag):
flag = True wait value from server, false does not wait value from server. |
- Retrieve a current value
Code Block |
---|
GetObjectValue(name)
name = TagName |
- Set a new value for an object
Code Block |
---|
SetObjectValue(name, newValue)
name = TagName
newValue = new value to set in the tag. |
- Execute a method from a remote ScriptClass
Code Block |
---|
ExecuteClassMethodOnServer(className, methodName, parameters)
className = name of the class in the remote project.
methodName = name of the method in the remote class.
parameters = if any, necessary to the invoke the remove method. |
Example
The sections below contain different ways to use Python in a project.
Using Namespace in CodeBehind
In this example, there are two input parameters called val1 and val2 that will be summarized and the result will be stored in the result variable.
The code that executes this action is presented below.
Code Block |
---|
//Defining where locate the .py files that will use
string pyDefinition = @Info.GetExecutionFolder() + @"\Calc\algorithm.py"; string pyWorkingFolder = @Info.GetExecutionFolder();
try
{
string error;
Dictionary<string, object> param = new Dictionary<string, object>();
//Defining the used imports from Python
string imports = "";
imports += "import sys" + Environment.NewLine;
imports += "from Calc.algorithm import Algorithm" + Environment.NewLine;
//Creating a .Net object from a Python object
object algorithm =Python.CreatePythonObjectFromPyFile(pyDefinition, "Algorithm", null);
//Creating a .Net object from a Python object
object val1 = Python.ToPython(@Tag.val1);
object val2 = Python.ToPython(@Tag.val2);
//Setting the parameters with the .Net objects that will be used to execute the Python code
param.Clear(); param.Add("algorithm", algorithm); param.Add("val1", val1);
param.Add("val2", val2);
//Call method to execute Python code
error = Python.ExecuteCode("result = algorithm.Sum(val1, val2)", pyWorkingFolder, param, true);
if (!string.IsNullOrEmpty(error))
throw new Exception(error);
//Set .Net object with result Python object , return of algorithm.Sum Python method
object result = param["result"];
//Copy .Net object to Tag
Python.CopyPythonObjectToTag(result, @Tag.result.GetName());
}
catch (Exception ex)
{
@Info.Trace("Python: " + (ex.InnerException == null ? ex.Message : ex.InnerException.Message));
}
|
Using Tasks
In this scenario, we configure a task for the Python language. In the Python file name field, you need to set the Python file that will be executed. In this example, we used the Main2.py.
In the Standard Output field, we selected a tag called output. This tag type must be text. In the Arguments field, we selected another type of tag called script.
Using the print method, the Python file called Main2.py retrieves the input data and outputs its value inside a string. The sys.argv will receive the Tag.script and the output tag will receive all the values from the print() method.
Code Block |
---|
import sys
value = sys.argv[1] print("Value: " + value) print("That’s all folks!") |
Using TKDataAccess.Py
In this example, you need to call a file named Main.py, which contains code that copies the content from tag1 (source) to tag2 (target).
The Python code using the TKDataAccess.py module in Main.py is described below:
Code Block |
---|
import sys
from Extensions.TKDataAccess import TKDataAccess dataAccess = TKDataAccess()
connectionStatus = dataAccess.Connect("127.0.0.1:3101", "guest", "") print("Connection: " + connectionStatus)
if dataAccess.IsConnected() :
ret = dataAccess.GetObjectValue("Tag.tag1") print("Value: " + str(ret)) dataAccess.SetObjectValue("Tag.tag2", ret)
dataAccess.Disconnect() |
Then, you need to create the code that is shown below or create a Python Script Task that executes the Main.py file, which contains the calling for TKDataAccess shown above. So here, we will use the Python namespace as previously described.
The code is shown below.
Code Block |
---|
try
{
string error = Python.ExecutePyFile(@Info.GetExecutionFolder() + @"\Main.py", null, true); if (!string.IsNullOrEmpty(error))
throw new Exception(error);
}
catch (Exception ex)
{
@Info.Trace("Python: " + (ex.InnerException == null ? ex.Message : ex.InnerException.Message));
} |
Note |
---|
To use the Python namespace, you need to install Python for .NET. |
Page Tree | ||
---|---|---|
|