You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 29 Next »

Overview

FrameworX takes the Python integration to the next level, with an unique set of features:

  • 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 FrameworX servers.


On this page:


Installation and Setup

The .NET integration is currently compatible and tested with Python releases 3.7 - 3.11. While earlier and newer versions may work with most features, they are not officially tested or supported.

Setup Steps:

    1.    Install Python on 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 Python interpreter, facilitating the development and maintenance of different solutions that may require different Python versions.

You can download Python here.

During the installation of the Python Engine, we strongly recommend choosing the option to “Install for all users”.

s


Go to Solution → Settings tab and locate for the Python GroupBox. Click the "..." button, navigate to find the installed Python Engine, and select the python.exe file.

Python Interpreter

Local

Defines the path for Python installation folder on the local machine.

Server

Defines the path for Python installation folder on the remote server.


Using Python in the Solution

Framework supports the shell activation of Python scripts from external files, created with other tools, and it also a has an integrator code editor, wit Python syntax highlighiting, and and a Test output console.

The Python code cabe used at:

  • Script-Tasks: event driven or periodical tasks, running in the server computer. 
  • Script Classes: library of methods and  functions that be used in both server and client machines, and by  Python, C# or VB.Net Code.
  • Displays CodeBehind: The entry point for the CodeBehind, is a .NET method, but right o first line you can call a Python class sro run the logic
  • Graphical Elements and Actions:  When definition the dynamic behavior of the Graphical Elements, the Action and the CodeBehind dynamics do asynchronous calla to server methods, which can be in Python.

Code Editor

The code editor is accessed at the Designer Scripts → Code Editor page

Testing your code

When the editor is used Script Tasks, you can test the scripts directly, using the Play button at the Task name line..The console standard output is redirection to the Designer output panel, showing the results of your code.

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 directly the properties, as shown in the image.

.NET Interoperability

Calling ScriptClass Methods

At the Script namespace, any code in your solution, call call methods defined on the script classes. 

@Script.Class.TestClass.ExempleMethod(param1, param2)

This activation is independent from the language the class was creating. Meaning C# and VB.NET can call Python classes, and Python code call .NET classes.




Extensibility Toolkit

We provide a toolkit in Python (TKDataAccess.py) which allows the Python code and application to interact with the Studio projects.








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
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
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
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)
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
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
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
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
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
public static string DumpPythonObjectToString(object pythonObject)

object pythonObject = Python object.
string returns = Dump information of object.


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).


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. 

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
Connect(runtimeHostAddress, userName, password):

runtimeHostAddress  =  IP address or server name
userName  = User name.
password = Password


  • Get a server connection status
GetConnectionStatus ()                 

           

  • Check your script's connection to the server
IsConnected ()


  • Disconnect from Server
Disconnect()


  • Set a flag waiting value from server
SetSyncFlag(flag):

flag = True wait value from server, false does not wait value from server.


  • Retrieve a current value
GetObjectValue(name)

name = TagName


  • Set a new value for an object
SetObjectValue(name, newValue)

name = TagName
newValue = new value to set in the tag.


  • Execute a method from a remote ScriptClass
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.

Examples

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.

//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 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 task 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.

import sys

value = sys.argv[1] print("Value: " + value) print("That’s  all  folks!")


To use the Python namespace, you need to install Python for .NET.


In this section:

The root page @parent could not be found in space v10.

  • No labels