← Back to list

Automating Mainframe Terminals with Python: An Introduction Guide

Mainframe automation has become a critical task in modern enterprise environments, enabling businesses to streamline processes, reduce…

Sam Nathan in In a Byte Size · 2024-12-11 16:41 · 1 claps · 2.0 min read paywalled
#python-automation #py3270 #read-mainframe-screen #terminal-automation
Open on Medium ↗

Automating Mainframe Terminals with Python: An Introduction Guide

Mainframe automation has become a critical task in modern enterprise environments, enabling businesses to streamline processes, reduce manual intervention, and minimize errors. In this article, we’ll explore how to automate mainframe terminal interactions using Python and avoid common pitfalls like hardcoding screen coordinates.

Understanding Mainframe Terminals

Mainframe terminals are text-based systems used to interact with enterprise environments, often leveraging IBM protocols like TN3270 or TN5250. Popular terminal emulators include:

  • x3270/s3270 (Open Source)
  • IBM Personal Communications (PCOMM)
  • Rocket BlueZone
  • Attachmate Reflection
  • Host On-Demand (HOD)

These emulators provide command-line or graphical interfaces for interacting with mainframes.

Why Avoid Hardcoding Screen Coordinates?

Hardcoding screen coordinates can make mainframe automation fragile, difficult to maintain, and prone to breakage when screens change. A better approach involves dynamic screen parsing and configuration-driven development.

Automating Mainframe Screens with Python

Step 1: Install Necessary Tools

Start by installing the necessary packages:

pip install py3270
sudo apt-get install x3270

Step 2: Connect to the Mainframe

Use the py3270 library to establish a connection to your mainframe terminal.

from py3270 import Emulator
# Initialize the emulator
em = Emulator(visible=False, executable='/usr/bin/s3270')
# Connect to the mainframe host
em.connect('<mainframe_host>')
# Send credentials
em.send_string('username')
em.send_enter()
em.send_string('password')
em.send_enter()

Step 3: Read Screen Coordinates Dynamically

Instead of hardcoding screen coordinates, implement a function that searches for specific labels on the screen.

def get_field_by_label(em, label_text):
    screen_text = em.screen_get()
    for row, line in enumerate(screen_text.splitlines(), start=1):
        if label_text in line:
            col = line.index(label_text) + len(label_text)
            return row, col
    return None
row, col = get_field_by_label(em, "Account Number:")
value = em.string_get(row, col, 15)
print(f"Account Number: {value}")

Step 4: Use Regular Expressions

For even more dynamic parsing, use Python’s re module to extract values from screen text.

import re
def extract_value(screen_text, label):
    pattern = re.compile(rf"{label}\s+(\w+)")
    match = pattern.search(screen_text)
    if match:
        return match.group(1)
    return None
screen_text = em.screen_get()
account_number = extract_value(screen_text, "Account Number:")
print(f"Account Number: {account_number}")

Step 5: Use a Configuration File

To fully eliminate hardcoding, store field labels in a configuration file (config.json):

{
    "account_number": "Account Number:",
    "user_id": "User ID:",
    "balance": "Balance:"
}

Then load the configuration file dynamically:

import json
def load_config(filename):
    with open(filename, 'r') as file:
        return json.load(file)
config = load_config("config.json")
# Extract based on config labels
for field, label in config.items():
    value = extract_value(em.screen_get(), label)
    print(f"{field.capitalize()}: {value}")

Step 6: Create a Python Class for Abstraction

Encapsulate the mainframe logic into a reusable class:

class MainframeSession:
    def __init__(self, host, executable='/usr/bin/s3270'):
        self.em = Emulator(visible=False, executable=executable)
        self.em.connect(host)
    def login(self, username, password):
        self.em.send_string(username)
        self.em.send_enter()
        self.em.send_string(password)
        self.em.send_enter()
    def read_field(self, label):
        screen_text = self.em.screen_get()
        return extract_value(screen_text, label)
    def close(self):
        self.em.terminate()
# Example Usage
session = MainframeSession("<mainframe_host>")
session.login("username", "password")
account_number = session.read_field("Account Number:")
print(f"Account Number: {account_number}")
session.close()

Best Practices for Mainframe Automation

  • Avoid Hardcoding Coordinates: Use labels and text parsing.
  • Externalize Configurations: Use JSON or YAML files.
  • Implement Dynamic Parsing: Use regular expressions for flexible data extraction.
  • Handle Errors Gracefully: Manage connection failures and unexpected screens.
  • Add Logging: Record screen content during failures for troubleshooting.

Final Thoughts

By following these best practices, you can build a scalable and maintainable automation framework for mainframe systems using Python. Say goodbye to fragile, hardcoded coordinates and embrace dynamic, label-based screen automation!


메타데이터
post_id
ff1dfcb46eea
slug
automating-mainframe-terminals-with-python-an-introduction-guide-ff1dfcb46eea
url
https://medium.com/in-a-byte-size/automating-mainframe-terminals-with-python-an-introduction-guide-ff1dfcb46eea
canonical_url
https://medium.com/in-a-byte-size/automating-mainframe-terminals-with-python-an-introduction-guide-ff1dfcb46eea
author_url
https://medium.com/@sajivkamalakar
status
ok
fetched_at
2026-06-09 15:37:30