PyLink: Python J-Link Interface
PyLink is a Python package that provides an interface to SEGGER J-Link debug probes, allowing control and interaction with embedded targets from Python. It was developed by Square to integrate J-Link functionality into Python-based test infrastructure. The library is actively maintained, with the current version being 2.0.1, and typically sees updates for new features and bug fixes.
Warnings
- breaking Python 2 support has been entirely dropped starting from PyLink version 2.0.0. Projects still using Python 2 will need to upgrade their Python environment or use an older version of PyLink.
- gotcha PyLink requires the SEGGER J-Link Software and Development Pack to be installed on the system, as it wraps the native C SDK. The library will not function without the underlying J-Link shared library (DLL on Windows, .dylib on macOS, .so on Linux) being present and discoverable by PyLink.
- gotcha Many operations, such as `open()`, `connect()`, `flash()`, and `erase()`, can raise 'Unspecified Error' exceptions. Common causes include: J-Link not physically connected, J-Link being used by another application, incorrect target device name, incorrect interface (JTAG vs. SWD), target not powered/connected, or the device not being properly halted before an operation.
- gotcha File paths passed to PyLink APIs (e.g., for flashing firmware) are now encoded using `os.fsencode()` to properly support UTF-8 file paths. If your application was implicitly relying on different encoding behavior for file paths prior to v2.0.0, this change might affect how non-ASCII paths are handled.
Install
-
pip install pylink-square
Imports
- JLink
from pylink import JLink
- pylink
import pylink
Quickstart
import pylink
import os
# Replace with your J-Link's actual serial number (as a string).
# Consider setting JLINK_SERIAL_NO and JLINK_TARGET_DEVICE as environment variables.
jlink_serial_no = os.environ.get('JLINK_SERIAL_NO', 'YOUR_JLINK_SERIAL_HERE')
target_device = os.environ.get('JLINK_TARGET_DEVICE', 'CORTEX-M4') # Example: 'ATSAM4S2B' or 'STM32F407VG'
try:
# Initialize JLink object
jlink = pylink.JLink()
# Open a connection to your J-Link probe
jlink.open(serial_no=int(jlink_serial_no))
print(f"Connected to J-Link: {jlink.product_name} (Serial: {jlink_serial_no})")
# Connect to the target device
jlink.connect(target_device, verbose=True)
print(f"Connected to target device: {target_device}")
# Perform a simple operation, e.g., read target IDCODE
if jlink.connected() and jlink.target_connected():
print(f"Target IDCODE: {hex(jlink.idcode())}")
# Example: Reset the target
# jlink.reset()
else:
print("Failed to establish full connection to target device.")
except pylink.JLinkException as e:
print(f"J-Link operation failed: {e}")
except ValueError:
print("Invalid J-Link serial number provided. Must be an integer.")
finally:
# Always close the J-Link connection
if 'jlink' in locals() and jlink.opened():
jlink.close()
print("J-Link connection closed.")