Versions Compared

Key

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

Bidirectional integration enabling Python's data science ecosystem within .NET's FrameworX

PlatformPython and .NET Integration | Tutorial | Reference


Integration Philosophy: FrameworX provides true bidirectional integration between Python and .NET, not just Python scripting capability. This design leverages Python's extensive data science libraries while maintaining .NET's performance and reliability for industrial control.

The platform requires Python 3.7 or later, delivering significant performance improvements over Python 2. According to Python.org benchmarks, Python 3 runs approximately 10-30% faster than Python 2 in most scenarios, with some operations seeing 5x improvements

One liner.

Platform → TechnologyCoreReal-Time | AI-Ready | .NET | Native | UNSPython 

Python and .NET Integration: 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

    .

    Table of Contents
    maxLevel

    3

    2

    style

    minLevel

    none

    2

    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
    titleClick here to expand on how to Install Python

    You can download Python here.

    Check the Use admin privileges checkbox, and select Customize installation.

    Image Removed

    During the installation of the Python Engine,select the option to “Install for all users”.

    Image Removed

    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.

    Tip

    This image may be slightly different for your Python version, but always enable the options equivalent to:

    • Add Python.exe to PATH

    Especially in the production server.

    • Install with admin rights to all users,
    • Customize the installation to installation in the Program Files, instead of Users folder

    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.

    Image Removed

    Note

    Note: For Python versions above 3.12, Pythonnet is not available. For more information, visit their documentation.

    Expand
    titleClick here to expand on how the setup the Python location in the Designer
    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.

    Image Removed

    Python Interpreter

    Local

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

    Server

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

    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.

    Image Removed

    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:

    indent10px
    stylenone


    Image Added

    Image Added


    Language Selection Guide

    LanguageBest ForPerformanceKey Features
    C#Complex logic, performance-critical operationsExcellentFull .NET access, strongly typed, IntelliSense
    PythonData analysis, ML integrationGoodExtensive libraries, NumPy/Pandas support

    Quick Selection Criteria

    • C# - Maximum performance, real-time control, type safety
    • Python - Data science, machine learning, rapid prototyping
    • Both - C# for control logic, Python for analytics

    Integration Patterns

    1. Embedded Python Scripts

    Python code runs within FrameworX's Script Tasks and Classes, with full access to tags and namespaces:

    # Python accessing FrameworX tags
    @Tag.Temperature = @Tag.SetPoint + 5
    result = ProcessData(@Tag.ProductionRate)

    2. Shell Integration

    Execute external Python files while maintaining tag access:

    result = TK.ExecutePythonShell("analytics.py", [@Tag.Input1, @Tag.Input2])
    @Tag.Result = result

    Info
    titleTest Playground

    When the editor is used to edit Script Tasks, you can test the scripts directly, using the Play Image Added button at the Task name line. The results of your code will show in the standard Designer output.


    3. Cross-Language Calls

    C# calling Python:

    // C# code calling Python class
    var result = @Script.Class.PythonAnalytics.ProcessML(data);

    Python calling C#:

    # Python code calling C# method
    result = @Script.Class.CSharpLogic.Calculate(param1, param2)

    Direct Access Architecture

    Python code accesses FrameworX objects directly through the same '@' notation used in C#:

    • @Tag - Real-time tag values
    • @Dataset - Database queries
    • @Alarm - Alarm states
    • @Historian - Time-series data

    No marshaling, conversion, or intermediate layers, Python operates on the same objects as .NET code.


    Development Environment

    Solution-Specific Python

    Each solution specifies its Python interpreter, enabling:

    • Different Python versions per project
    • Isolated package environments
    • Consistent deployment across development and production

    In-Designer Features

    • Code Editor - Python syntax highlighting and IntelliSense
    • Testing - Run Python scripts directly in Designer
    • Debugging - Output window for print statements and errors
    • Tag Access - Auto-completion for all namespace objects

    Industrial Use Cases

    Machine Learning Integration

    # Use scikit-learn for anomaly detection
    from sklearn.ensemble import IsolationForest
    model = IsolationForest()
    data = GetHistorianData(@Tag.Equipment)
    anomalies = model.fit_predict(data)

    Data Analysis

    # Pandas for production analytics
    import pandas as pd
    df = pd.DataFrame(@Dataset.Query("SELECT * FROM Production"))
    daily_avg = df.groupby('Day')['Output'].mean()
    @Tag.DailyAverage = daily_avg.iloc[-1]

    Custom Protocols

    # Implement proprietary protocol
    import struct
    packet = struct.pack('>HH', @Tag.DeviceID, @Tag.Command)
    response = SendCustomProtocol(packet)
    @Tag.Response = struct.unpack('>H', response)[0]

    System Requirements

    • Python Version: 3.7 or later (3.11 recommended)
    • Python.NET: Required for integration (pip install pythonnet)
    • Installation: System-wide (all users) for service deployment
    • Path: Python.exe must be in system PATH



    Performance Considerations

    Operation TypeRecommendedReason
    Real-time control loopsC#Deterministic execution, minimal latency
    Statistical analysisPythonNumPy/Pandas optimized C libraries
    Tag calculationsC#Direct memory access, no interpreter
    Machine learning inferencePythonScikit-learn, TensorFlow ecosystems
    Database operationsEitherBoth have excellent SQL support

    Key Advantages

    • No Bridge Required - Direct integration via Python.NET
    • Shared Memory Space - Zero-copy data access between languages
    • Production Ready - Runs as Windows service, handles 24/7 operation
    • Version Flexibility - Multiple Python versions on same server
    • Library Access - Full Python Package Index (PyPI) availability


    Excerpt

    Explanation - to understand concepts

    Platform / Technology Foundation / Python and .NET Integration

    Tutorials - to learn by doing

    Tutorials /  Technology Learning / Python and .NET Integration

    Reference - technical details

    → Technical Reference / Programming and APIs Reference / Python and .NET Integration




    In this section...

    Page Tree
    root@parent
    spaces93DRAF

    Code Block
    languagepy
    titleShell Integration example
    # 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
    titlePython Shell Version and Tests

    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.

    Image Removed

    Testing the code

    When the editor is used to edit Script Tasks, you can test the scripts directly, using the Play Image Removed 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
    languagepy
    @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:

    Page Tree
    root@parent