The industrial automation landscape is undergoing a transformation. For decades, the role of automation professionals centered on mastering field signals, electrical panel design, and PLC programming. While this skill set remains essential, it is no longer sufficient.
Decentralized decision-making processes and the demand for increasingly connected plants are redefining the profiles required by the market. Mastery of IEC 61131-3 languages, such as Ladder Diagram, continues to serve as the foundation of process control. However, new requirements are gaining significant weight in engineering projects: connectivity, data processing, and system integration.
In this context, Python has emerged as the new indispensable tool for automation professionals. Far from competing with deterministic hardware control systems, Python acts as a flexible bridge that fills the gaps traditional controllers were not designed to handle easily—such as mathematical calculations on historical data, web API connections, and intelligent report management.
Learning Python is, today, a strategic skill for anyone needing to adapt to the digitization demands of Industry 4.0. Below, see how to start understanding the language and applying it to automation projects.
Why is Python gaining ground in automation?
The adoption of Python in industrial automation is not a fleeting trend; it is a strategic response to real market demands for sector modernization. The Brazilian technology market reflects this transformation: while cloud computing expands across national operations, Artificial Intelligence adoption in industry shows significant growth, laying the groundwork for more predictive and autonomous production processes.
Python stands out in this scenario for three key reasons:
Accessibility: Its clean syntax, built on mandatory indentation and free from the structural redundancies typical of lower-level languages, allows technicians and engineers accustomed to hardware logic to quickly transition into software development.
Cost-efficiency: Being open-source and free from licensing restrictions, Python eliminates expenses that previously fell on proprietary software.
Ecosystem: A vast global community maintains thousands of ready-to-use libraries for industrial communication, predictive analytics, and machine learning. This allows professionals to connect the shop floor to databases and IoT platforms without having to build communication drivers from scratch.
Below is a comparison between the IEC 61131-3 standard and the role Python plays in an industrial environment:
Operating feature | IEC 61131-3 | Python |
Real time & determinism | High (deterministic and ultra-fast); optimized microsecond-level processing. | Ideal for asynchronous tasks above the physical control layer. |
| Execution logic | Sequential and cyclic (continuous input/output scan). | Linear, event-driven, or object-oriented. |
| Data complexity | Limited to basic data types, boolean variables, and simple static arrays. | Native support for complex data structures, dictionaries, JSON, and Big Data tables. |
| Typical applications | Safety interlocks, high-speed PID loops, and machine sequencing. | Data analytics, predictive maintenance, production report generation, and web connectivity. |
| Scalability cost | High; often dependent on licensing additional tags and proprietary drivers. | Free; open-source with no cost per execution volume or connectors. |
Where can an integrator use Python in practice?
Python does not compete with the PLC. While the controller manages direct control over motors, valves, and emergency shutdown systems, Python operates in the higher automation layers, where flexibility and integration capabilities make all the difference.
It is in this space that the language expands the capabilities of existing assets, enabling connectivity solutions and operational routine optimizations that deterministic control systems were not designed to handle easily, such as:
Operational data collection and monitoring: Using widely established industrial communication protocols, Python scripts send requests to controllers from different vendors. An integrator can develop automated polling routines that extract temperature sensor values or fault logs directly from PLC registers, organizing this information without interfering with the main program’s scan time.
Interoperability with OPC UA: The opcua library (or its asynchronous variant, asyncua) makes it easy to build OPC UA clients and servers. The Python script establishes encrypted connections with OPC UA servers built into global machinery, dynamically browsing the plant’s address space to read and write variables with security and data integrity. For pre-deployment validation, tools like Prosys OPC UA Simulation Server or UAExpert allow testing data exchanges in a simulated environment.
Direct integration with relational and NoSQL databases: Unlike traditional HMIs and SCADA systems that charge extra licensing fees for database drivers, Python natively connects to virtually any storage infrastructure. Field variables can be streamed directly to Microsoft SQL Server, MariaDB, PostgreSQL, or Oracle via direct connectors or through the SQLAlchemy Object-Relational Mapper (ORM). For benchtop prototypes, the embedded SQLite database is available out-of-the-box via the sqlite3 library, requiring no dedicated servers.
Automation of reports and interactive dashboards: Consolidating information into spreadsheets manually consumes hours of work and introduces human error. With pandas and openpyxl, Python automates opening, reading, filtering, and restructuring hundreds of production files in seconds. The output can be generated as static PDF reports or fed directly into interactive dashboards built with frameworks like Streamlit or Dash, displaying real-time OEE metrics and key performance indicators.
IoT connectivity with MQTT: For projects requiring continuous communication with cloud platforms, Python integrates seamlessly with the MQTT protocol using the paho-mqtt library. Operating on a publish/subscribe architecture with “report by exception,” data is transmitted only when a variable state changes. This approach minimizes bandwidth consumption over 3G/4G/5G cellular networks used in remote monitoring stations.
However, to guarantee the performance and stability of field networks where these systems operate, integrators must understand how different protocol models handle information exchange:
| Communication model | Protocol | Operating mechanism | Impact on bandwidth and latency |
| Master / Slave (Mestre/Escravo) | Modbus RTU | The master makes sequential requests to each slave on the network, which responds only when queried. | Relatively inefficient bandwidth usage in networks with many devices; latency increases as the node count and scan time grow. |
| Client / Server | Modbus TCP, OPC UA | The client establishes a connection with the server to read or write data on demand. | Moderate latency; requires active server processing to manage open sessions. |
| Producer / Consumer | EtherNet/IP | The producer sends data once onto the network (typically via multicast), allowing multiple consumers to receive it simultaneously. | Extremely high bandwidth efficiency; very low latency, ideal for fast synchronization in distributed control. |
| Publisher / Subscriber | MQTT | Devices publish messages (payloads) to specific topics on an intermediary Broker; subscribers receive data asynchronously by exception. | Minimal bandwidth consumption; perfect for cloud telemetry of geographically dispersed assets. |
How to apply Python in legacy installations
One of the greatest challenges for an industrial integrator is dealing with plants operating with legacy equipment, outdated HMIs, and PLCs that lack cloud connectivity or support for modern protocols. Completely replacing a fully functional control system is rarely feasible: the cost is high, and the risk of downtime during commissioning is significant.
Python solves this equation by acting as a complementary, non-invasive software layer, extracting, standardizing, and unifying data from legacy systems without disturbing the logic controlling the physical process.
In an application featuring, for instance, several older PLCs communicating solely over RS-485 serial networks using the Modbus RTU protocol, an integrator can attach a laptop running a Python script physically connected to the controllers’ serial channel to gradually digitize the plant. To accomplish this, the script operates through well-defined steps:
- Serial reading and polling: Using the
ModbusSerialClientmodule from thepymodbuslibrary, the script establishes communication with the physical port (COM3on Windows or/dev/ttyUSB0on Linux), configuring the exact channel parameters: baud rate, stop bits, and parity. It then performs cyclic polling of the holding registers or coils for each PLC configured as a slave node.
- Data processing and conversion: The raw values returned by the PLC arrive as arrays of 16-bit integers. The Python script processes this information by applying mathematical scaling operations, combining two 16-bit registers into a single 32-bit floating-point value, or converting the data into engineering units.
- Read and write error handling: On older PLCs, write attempts may fail due to internal memory protections or the incorrect use of function codes, such as trying to write data with Function 06 into read-only input registers (Function 04). Python handles these anomalies using
try/exceptblocks, logging fault details and preventing the overall communication process from crashing.
- Standardization and transmission to IT: After processing and converting the variables into floats or strings, the script organizes the data into a structured, unified JSON object. This payload is simultaneously transmitted via HTTPS using the
requestslibrary to a corporate REST API or published to encrypted MQTT topics in the cloud.
The result is a facility built decades ago now serving operational metrics directly to modern dashboards, without major capital expenditure (CapEx) and with zero line downtime.
Read more: Python application in the industry: control logic for smart automation
How to start learning Python
Transitioning from graphical programming languages like Ladder Diagram to a text-based, interpreted language requires a clear strategy. The most effective approach is to begin with fundamental concepts applied directly to your technical domain, gradually advancing toward real-world hardware integration.
Master basic syntax and control flow: Start by understanding variable assignment, loops (for, while), and conditional statements. Building mental parallels with Ladder logic helps accelerate assimilation.
Practice exception handling early: In industrial environments, network cables disconnect, PLCs lose power, and noise interferes with serial ports. Python’s try/except structures provide the mechanism to handle these faults gracefully without crashing your monitoring application.
Build hands-on projects from day one: A great initial project is creating a benchtop datalogger. Set up a PLC simulator on your computer (such as the integrated simulator in CODESYS or TIA Portal) and write a Python script to read simulated analog variables and log them to an Excel spreadsheet using libraries like pandas or openpyxl. As a next step, add a conditional check to monitor whether a temperature variable exceeds a threshold and trigger an email or SMS notification via the requests library when an alert occurs.
Common pitfalls when transitioning to Python
When starting out, automation professionals frequently encounter errors stemming from the programming paradigm shift. Knowing these in advance saves time and frustration:
Indentation errors: In languages like Structured Text (ST), semicolons and explicit delimiters (END_IF, END_FOR) define code blocks. In Python, left-side indentation itself defines the logical block structure. Mixing spaces and tabs or misaligning a single line triggers an IndentationError. Using an IDE such as Visual Studio Code with Python extension support helps prevent and automatically format these issues.
Dynamic typing bugs: PLCs operate in strictly typed environments where REAL and INT variables are declared before compilation. Python assigns types dynamically at runtime. Attempting to perform arithmetic on an analog value read from a PLC in string format, without first converting it to a float, causes runtime exceptions or unexpected results.
Using Python instead of a PLC for critical control: This is the most critical mistake. Python runs on general-purpose operating systems with non-deterministic task scheduling, which can introduce unpredictable millisecond-level latency when driving physical outputs. Safety logic, equipment protection, and high-speed motion synchronization must always remain where they belong: on the PLC’s real-time processor.
Key libraries worth knowing
To accelerate project development, Python offers an extensive ecosystem of pre-built packages tailored for industrial communication, data manipulation, and web connectivity:
| Library | Main function | Use example |
pandas | Analysis and manipulation of large tabular datasets (structured in DataFrames). | Importing historical CSV production logs, filtering active alarms, and exporting executive reports to Excel. |
NumPy | Optimized numerical processing and high-speed vector operations based on C-level mathematical structures. | Calculating standard deviation averages and processing high-frequency motor vibration curves. |
matplotlib | Generation of static charts, trend diagrams, and data plots. | Generating temperature vs. pressure scatter plots for quality control audits. |
pymodbus | High-level, open-source implementation of Modbus TCP and Modbus RTU (serial) protocols. | Connecting Python scripts directly to variable frequency drives (VFDs) or energy meters to read operating current in real time. |
opcua (ou asyncua) | Full, secure connectivity based on the standardized open architecture of the OPC UA protocol. | Establishing a secure client to read symbolic tags and log diagnostics directly from a plant PLC’s OPC UA server. |
requests | Simplified HTTP web requests for interacting with cloud-based APIs. | Sending payloads with structured JSON production logs to a web service or corporate database. |
python-snap7 | Dedicated connection for direct data exchange with controller data blocks (DBs). | Creating automated routines for direct data block (DB) read and write operations without requiring intermediary gateways. |
pycomm3 | Native communication library utilizing the Common Industrial Protocol (CIP). | Dynamically reading and writing internal controller tags. |
The future of automation lies in the convergence of control and data
The flow of operational data in modern plants demands distributed and flexible processing architectures, so-called Edge Computing. Automation manufacturers like Altus are keeping pace with this transition by delivering integrated platforms that bring together the best of both worlds.
Our programming software, Mastertool, built on the CODESYS platform, enables the development of deterministic interlock logic using IEC 61131-3 languages. Meanwhile, on high-performance CPUs such as the NX3008 and Nexto XF line controllers, the system features embedded Docker support running alongside high-speed processors, opening up an additional layer of intelligence directly on the PLC.
This environment allows for the deployment of complete virtualization solutions using container technology to execute Python code side-by-side with the classic logical control CPU:
- Deterministic critical control: The PLC’s real-time execution engine (CODESYS RT) manages analog PID loops with millisecond precision and actuates physical I/O modules with maximum operational safety—completely isolated from interference from the IT layer.
- Asynchronous IT layer: In parallel, within a virtualized Linux environment isolated via Docker, the Python interpreter processes predictive data locally at the source, monitors diagnostic logs from the processor itself, and transmits information to enterprise systems without competing for resources with real-time control.
- Layered cybersecurity: To protect the shop floor against threats arising from expanded network connectivity, Nexto System controllers feature a fully configurable firewall via web interface, support for encrypted VPN channels, and strict authenticated access control.
The result is the centralization of control, virtualization, and intelligent data analysis into a single field device, eliminating the need for additional industrial PCs or protocol converters on the plant network.
As highlighted throughout this article, adopting Python in industrial automation does not mean abandoning traditional engineering tools or replacing established languages like Ladder Diagram. Control logic remains where it has always been: inside the PLC.
The transition can begin simply, through the use of local simulators and basic scripts for logging and alert notifications. Over time, as skills naturally mature, new development horizons open up, all the way to modern controllers with embedded Linux, where Python and control logic operate side-by-side on a single, unified platform.