Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
FactoryStudio now includes Python as a programming language you can use in
Tip

Texto geral

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.

A integração com o Python abre uma ótima maneira de desenvolver algoritmos de IA aos seus projetos. Aumente o poder e o alcance de seu código Python existente integrando-o ao Action˳NET.

Visão geral

A programação em muitos de seus projetos consistirá em código C # ou VB.Net 100% Managed , projetado para ser executado no framework Microsoft .NET.

O Action.NET agora inclui Python como uma linguagem de programação que pode ser usada em 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.

Factory Studio 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:

  • 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 (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.

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

Image Removed

Now you need to 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, and select the python.exe file.

Image Removed

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, navigate to Scripts Tasks, select a new, blank row, and double-click on the Code column. After clicking Code, a combobox will appear. Select Python from the combobox. 

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

Image Removed

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

Image Removed

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)

After making any changes, click the Apply Changes button.

Python Namespace

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

e interativamente por meio de código Python externo.

Python é uma linguagem interpretada, de alto nível e de uso geral. É uma linguagem popular para Inteligencia Artificial (AI) e Machine Learning(ML), que é muito útil para utilização em algoritmos como os de manutenção preditiva.

O Action.NET pode usar qualquer versão do Python, 3.x ou a mais antiga e passada 2.x.

Os usuários podem usar Python de três maneiras diferentes:

  • Usando Script> Task: Para Python: execute o código Python (.PY) e use a interface Script Task para definir e obter parâmetros (nenhum código é necessário no Studio).

  • Namespace Python (Python para .Net): Crie código .Net usando o namespace Python para interagir com os objetos Python.

  • Python usando o kit de ferramentas TKDataAccess: Crie o código Python usando o TKDataAccess.py (fornecido por nós) para interagir com os projetos do Studio.

Requisitos de sistema

Intérprete Python

A primeira etapa para usar a programação Python é incluir um link para a versão do interpretador Python que você deseja usar em seu projeto. Você pode baixar Python aqui.

Durante a instalação do Python Engine, é altamente recomendável escolher a opção “Instalar para todos os usuários”.

Image Added

Agora você precisa adicionar o intérprete ao seu projeto. Navegue até a guia Info>Settings e vá ao quadro Python. Clique no botão, navegue para encontrar o Python Engine instalado e selecione o arquivo python.exe.

Image Added

Python para .Net

Python for .NET é um pacote que oferece aos programadores Python uma integração quase perfeita com o .NET Common Language Runtime (CLR) e fornece uma ferramenta de script de aplicativo poderosa para desenvolvedores .NET.

Python para .NET permite que o código Python interaja com o CLR e pode ser usado para embutir Python em um aplicativo .NET. Os arquivos de instalação e documentação estão disponíveis aqui.

Verifique se suas versões do Python e do Windows são de 32 ou 64 bits antes de baixar o Python para .NET. Isso é necessário apenas se você pretende usar o namespace Python em Studio Scripts e Display CodeBehinds.

Criação de scripts em Python

Para criar scripts com base na linguagem de programação Python, navegue até Scripts> Tarefas, selecione uma nova linha em branco e clique duas vezes na coluna Código. Depois de clicar em Código, uma caixa de combinação aparecerá. Selecione Python na combobox.

Note

Depois que uma nova tarefa é criada, o tipo de idioma não pode ser alterado por meio da coluna Código

Image Added

Depois de criar uma nova tarefa de script, você precisa editá-la na guia CodeEditor.

Image Added

As configurações são detalhadas a seguir:

  • Nome do arquivo: Nome do arquivo .py

  • Saída padrão: nome da tag que receberá todas as saídas impressas via impressão

  • Argumentos: Lista de argumentos. Esta lista de parâmetros será passada como argumentos para o Python Engine (python.exe)

Depois de fazer qualquer alteração, clique no botão Apply Changes (Aplicar alterações.

Python Namespace

O namespace Python pode ser usado em qualquer editor de script (Tarefas, Classes ou CodeBehind) dentro do ambiente do projeto. Para usar o namespace Python, você simplesmente precisa instalar o pacotePython.NET, disponível no github.

O namespace Python fornece vários métodos .Net que interagem com códigos e objetos Python. Veja alguns desses métodos abaixo:

Execute um arquivo .py usando Python para .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

Execute um código Python usando Python para .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

Converta um valor Python em um valor .NET

value

Code Block
public static object FromPython(object value)
 
object value = Python value
object returns = NET value
Copy a Python object to a

Copiar um objeto Python para uma tag (Array

or

ou 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

Copie uma tag (Array

or

ou User Template)

to a

para um objeto 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

Crie um objeto Python a partir de uma classe Python

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

Obtenha todos os atributos de um objeto Python

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

Defina um novo valor para os atributos de um objeto Python

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

Despeje um objeto Python em uma string para enviá-lo a uma TraceWindow

Code Block
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
Info

Se você precisar instalar outros módulos Python e bibliotecas (como numpy, pythonnet, matplotlib, etc.),

you must install them in the same location as

você deve instalá-los no mesmo local que o Python Engine (python.exe).

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

Note

Todos os métodos listados acima estão desativados para projetos Mono e exibições HTML5.

TKDataAccess.py

You can create code in the Python environment and use the TKDataAccess.py file to interact with the projects. 

Tatsoft provides the TKDataAccess.py file. When you use it, you need to make sure the installPath into the TKDataAccess.py file is with the correct path of the FactoryStudio installation.

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

Open a connection with the server

Você pode criar código no ambiente Python e usar o arquivo TKDataAccess.py para interagir com os projetos.

O Action.NET fornece o arquivo TKDataAccess.py. Ao usá-lo, você precisa ter certeza de que o installPath no arquivo TKDataAccess.py está com o caminho correto da instalação do Action.NET.

Abaixo estão alguns métodos de TKDataAccess.py que você pode usar:

  • Abra uma conexão com o servidor

    Code Block
    Connect(runtimeHostAddress, userName, password):
     
    runtimeHostAddress  =  IP address or server name
    userName  = User name.
    password = Password

  • Get a server connection statusObtenha um status de conexão do servidor

    Code Block
    GetConnectionStatus ()                 

           

  • Check your script's connection to the serverVerifique a conexão do seu script com o servidor

    Code Block
    IsConnected ()

  • Disconnect from ServerDesconectar do servidor

Code Block
Disconnect()
  • Set a flag waiting value from serverDefina um flag de espera de um valor do servidor

    Code Block
    SetSyncFlag(flag):
  •  
    flag = True wait value from server, false does not wait value from server.

  • Retrieve a current valueRecupere um valor atual

Code Block
GetObjectValue(name)
 
name = TagName

  • Set a new value for an objectDefina um novo valor para um objeto

Code Block
SetObjectValue(name, newValue)
 
name = TagName
newValue = new value to set in the tag.
  • Execute a method from a remote ScriptClassum método de um ScriptClass remoto

    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

Examplo

As seções a seguir contêm diferentes maneiras de usar Python em um projeto.

Usando namespace em CodeBehind

Neste exemplo, existem dois parâmetros de entrada chamados val1 e val2 que serão resumidos e o resultado será armazenado na variável de resultado.

O código que executa esta ação é apresentado a seguir.

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


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

Image Removed

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.Neste cenário, configuramos uma tarefa para a linguagem Python. No campo de nome do arquivo Python, você precisa definir o arquivo Python que será executado. Neste exemplo, usamos Main2.py.

No campo Saída padrão, selecionamos uma tag chamada output. Este tipo de tag deve ser texto. No campo Argumentos, selecionamos outro tipo de tag chamado script.

Usando o método de impressão, o arquivo Python chamado Main2.py recupera os dados de entrada e produz seu valor dentro de uma string. O sys.argv receberá o Tag.script e o tag de saída receberá todos os valores do método print ().

Image Added

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

Usando 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 belowNeste exemplo, você precisa chamar um arquivo denominado Main.py, que contém o código que copia o conteúdo de tag1 (origem) para tag2 (destino).

O código Python usando o módulo TKDataAccess.py em Main.py é descrito abaixo:

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 belowEntão, você precisa criar o código que é mostrado abaixo ou criar uma Tarefa de Script Python que execute o arquivo Main.py, que contém a chamada para TKDataAccess mostrado acima. Então, aqui, usaremos o namespace Python conforme descrito anteriormente.

O código é mostrado abaixo.

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));
}
To use the Python namespace, you need to install
Note

Para usar o namespace Python, você precisa instalar o Python for .NET.

@

Panel

@Nesta pagina:

Table of Contents
maxLevel2