Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Info
iconfalse

Quick video tutorial: Using Phyton Python with TK Data Access, Using Phyton Python with Script Task, Using Phyton Python with Code Behind (no audio)

Overview

In The programming in many of your projects , the programming will consist of C# or VB.Net 100% managed code that is designed to run in the Microsoft .NET framework.

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

In recent updates there has been an addition to a new programming language included: Python, an interpreter, high-level, general-purpose programming language. Factory Studio can use any version of Python even , 3.x or the older and past end-of-life 2.x. 


Users can use Python in three different ways:

  • 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).
  • Python namespace (Python for .Net): Create .Net code using the Python namespace to interact with the Python objects.
  • Python using TKDataAccess toolkit: Create Python code using the TKDataAccess.py (provide provided by us) 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

Interpreters and compilers are similar, since they both recognize and process source code. However, a compiler does not execute the code like an interpreter does. Instead, a compiler simply converts the source code into machine code, which can be run directly by the operating system as an executable program. Interpreters bypass the compilation process and execute the code directly.

To download the interpreter, use this link.

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



Now you need to include add the interpreter to your project. Navigate to Info > Settings tab and search for the Python field. Click on the button, browse to find the installed Python Engine that was installed, and select the python.exe file.

...

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.

It allows Python for .NET allows Python code to interact with the CLR , and may also be used to embed Python into a .NET application. The installation files and documentation are available in this linkhere.

Check to see whether your Python Engine version and if your Windows version is versions are 32-bit or 64-bit before choosing you download Python for .NET installation file. This is only required only if you intend to use the Python namespace in the Studio Scripts and Display CodeBehinds.

...

To create scripts based on the Python programming language, navigate to Scripts > Tasks, select a new, blank new row, and double-click on Code column. You should see Python available for selection in the ComboBox.the Code column. After clicking Code, a combobox will appear. Select Python from the combobox. 

Note

Once a new Task task is created, the language type cannot be altered through the Code Columncolumn.



After creating a new script task, you need to edit it through in the CodeEditor tab.



The configurations settings are detailed below:

  • 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, you need click the Apply Changes button.


...

Python Namespace

Must use for .Net developers, the The Python namespace can be used in any script editor inside your project environment (Tasks, Classes and , or CodeBehind) . Basically, all you need is to install Python for .NETinside 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 to that interact with Python codes and objects. See some of those methods below:                        

...

  • 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 others to install other Python modules and libraries (such as numpy, pythonnet, matplotlib, etc.) must be installed at , you must install them in the same location as Python Engine (python.exe).


Warning

Those All of the methods listed above are disabled for Mono project projects and HTML5 displays.


...

TKDataAccess.py

Must use for Python developers, you You can create code in the Python environment and use the TKDataAccess.py file to interact with the projects. 

Warning

Tatsoft provides the TKDataAccess.py is provided by Tatsoft, and when usedfile. When you use it, you need to make sure the installPath into the TKDataAccess.py file is with the correct path of Studio installation.it is installed in the same folder as FactoryStudio. 


Below are See below some methods from TKDataAccess.py that you can use:

...

Code Block
Connect(runtimeHostAddress, userName, password):

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


  • Get Status of Server Connection.a server connection status
Code Block
GetConnectionStatus ()                 

           

  • Check whether is connected to server.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

In the The sections below there are details on the contain different ways to use Python in a project. 

Using Namespace in CodeBehind

In this first example, there are two input parameters called val1 and val2 that will be summarized and the result will be stored in the result variable.

...

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 to that will be executed. In this example, we used the Main2.py.



In the Standard Output field, we put selected a Tag tag called output. This Tag tag type must be Texttext. In the Arguments fields type another Tag Arguments field, we selected another type of tag called script.

The Using the print method, the Python file called Main2.py gets the retrieves the input data and outputs its value inside a string, using the print method. Where the . 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 we will , 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 is .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, in the project you need to create a the code that is shown below or create a Python Script Task that executes the Main.py file that , which contains the calling for TKDataAccess as showed in shown above. So here, we will use the Python namespace as previously described.

...

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

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

...