Duet Software Framework Python Bindings
dsf-python is a Python client for the Duet Software Framework
(DSF) control server. It talks to DSF over its UNIX socket and provides:
dsf.connections: connections for sending commands, subscribing to the object model and intercepting codesdsf.object_model: the DSF object model as typed Python classesdsf.http: custom HTTP and WebSocket endpoints served through DSFdsf.commands: low-level builders for every DSF command
It follows the C# DuetAPIClient closely, but uses Python naming. See
Differences from the DSF API before porting C# code or reading the DSF docs.
Installation
python3 -m pip install dsf-python
Python 3.11 or newer is required. Your script must run on the machine that runs DSF, as a user
that can access the DSF socket (usually the dsf user). The socket path is read from
/opt/dsf/conf/config.json and falls back to /run/dsf/dcs.sock.
Quick Start
from dsf.connections import CommandConnection
connection = CommandConnection()
connection.connect()
try:
print(connection.perform_simple_code("M115"))
object_model = connection.get_object_model()
print(object_model.state.status.value)
print(object_model.state.up_time) # "upTime" in DSF
finally:
connection.close()
Connections
| Connection | Use it to | Example |
|---|---|---|
CommandConnection |
Run codes, evaluate expressions, read the object model, manage plugins, files and HTTP endpoints | send_commands.py |
SubscribeConnection |
Keep a local copy of the object model up to date and react to changes | subscribe_object_model.py |
InterceptConnection |
Handle custom M-codes, or inspect codes before or after DSF processes them | custom_m_codes.py |
Every connection is configured in its constructor, opened with connect() and closed with close().
Errors reported by DSF are raised as InternalServerException (with error_type and error_message),
or as TaskCanceledException if DSF cancelled the request.
SubscribeConnection
from dsf.connections import SubscribeConnection, SubscriptionMode
subscription = SubscribeConnection(SubscriptionMode.PATCH, filter_list=["state/status", "heat/heaters[*]/current"])
subscription.connect()
object_model = subscription.get_object_model() # First call: blocks for the full object model
def on_heater_changed(*, key, data, indices):
print(f"Heater {indices[0]} is now at {data}C")
unsubscribe = subscription.subscribe_to_keys(["heat.heaters.^.current"], on_heater_changed)
while True:
object_model = subscription.get_object_model() # Later calls: apply queued patches, run callbacks
...
- In
SubscriptionMode.PATCH, the firstget_object_model()call blocks until the full model arrives. Later calls do not block: they apply every queued patch to the cached model and return it. - In
SubscriptionMode.FULL, every call blocks until the next full object model arrives. subscribe_to_keys()callbacks run synchronously insideget_object_model(), only in patch mode, and receive the keyword argumentskey,data(the raw JSON value from the patch) andindices(the list indexes matched by^, orNone). Register them after the firstget_object_model()call. The return value removes the callback again.- DSF sends each message only once, so in patch mode
object_model.messagescollects the messages of every applied patch. By defaultget_object_model()clears it first, so it holds only the messages received since the previous call. WithSubscribeConnection(..., clear_messages=False)messages are kept until you clear the list.
InterceptConnection
from dsf.connections import InterceptConnection, InterceptionMode
from dsf.object_model import MessageType
interceptor = InterceptConnection(InterceptionMode.PRE, filters=["M1234"])
interceptor.connect()
while True:
code = interceptor.receive_code()
name = code.parameter("S", "world").string_value
interceptor.resolve_code(MessageType.SUCCESS, f"Hello {name}!")
Every intercepted code must be answered with resolve_code(), ignore_code() or cancel_code().
InterceptConnection also has all CommandConnection methods, so it can run other codes while a
code is intercepted, e.g. perform_simple_code("M117 hi", code.channel).
Custom HTTP Endpoints
from dsf.http import HttpEndpointConnection, HttpResponseType
from dsf.object_model import HttpEndpointType
async def hello(connection: HttpEndpointConnection) -> None:
request = await connection.read_request()
await connection.send_response(200, f"Hello {request.queries.get('name', 'world')}!", HttpResponseType.PLAIN_TEXT)
endpoint = command_connection.add_http_endpoint(HttpEndpointType.GET, "example", "hello")
endpoint.set_endpoint_handler(hello) # Serves GET /machine/example/hello in a background thread
...
command_connection.remove_http_endpoint(HttpEndpointType.GET, "example", "hello")
endpoint.close()
Differences From The DSF API
Naming
| DSF / C# | dsf-python | |
|---|---|---|
Attributes and methods are snake_case |
state.upTime, PerformSimpleCodeAsync() |
state.up_time, perform_simple_code() |
Enum members are UPPER_SNAKE_CASE |
MachineStatus.ChangingTool |
MachineStatus.CHANGING_TOOL |
| Uppercase acronyms | move.skew.tanXY |
move.skew.tan_XY (acronyms stay uppercase) |
| Global variables | global |
globals (global is a Python keyword) |
Anything passed to DSF as a string stays in DSF's camelCase format, because DSF interprets it and
not this library:
| Where | Format | Example |
|---|---|---|
SubscribeConnection(filter_list=...) |
/-separated, [*] for any list item, ** for everything below |
"heat/heaters[*]/current", "move/**" |
CommandConnection.get_object_model(filters) |
.-separated key paths |
["state", "move.axes"] |
SubscribeConnection.subscribe_to_keys(keys) |
.-separated, list indexes as numbers, ^ for any list item |
"heat.heaters.^.current", "move.axes.2.userPosition" |
evaluate_expression(), query_object_model(), G-code |
RepRapFirmware expressions | "state.upTime", "move.axes[0].homed" |
ObjectModel.update_from_json() and from_json() take DSF JSON (camelCase), and to_json() writes it back:
object_model.update_from_json({"state": {"upTime": 1234}})
object_model.state.up_time # 1234
object_model.to_json() # '{..."state": {..."upTime": 1234...}...}'
Behaviour
- Synchronous. Connection methods block and have no
Asyncsuffix orCancellationToken. Only HTTP endpoint handlers areasynccoroutines. - Configuration in the constructor. Options passed to C#
ConnectAsync()(mode, filters, channels,verbose, ...) are constructor arguments.connect()takes only an optional socket path. - Patches are applied for you.
SubscribeConnection.get_object_model()keeps an internal model up to date in patch mode. In C#, you apply patches fromGetObjectModelPatchAsync()yourself.get_object_model_patch()andget_serialized_object_model()still return raw JSON if you need it. - Key callbacks (
subscribe_to_keys()) are specific to dsf-python. - Messages are cleared for you. In C#, it is the developers responsibility to clear
Model.Messagesmanually. Theget_object_model()helper method clears them at the start of each call unlessclear_messages=False. - Return values. Connection methods return the same values as in C#. Only the lower-level
perform_command()returns aResponse, whose value is in.result. - Interception.
resolve_code()takes aMessageTypeand an optional string, not aMessage. There is norewrite_code().flush()takes a channel instead of flushing the intercepted code's channel. - HTTP endpoints. Handlers are registered with
set_endpoint_handler()instead of an event.add_http_endpoint()returns anHttpEndpointUnixSocket, which must be closed afterremove_http_endpoint().
Examples
| Example | Shows |
|---|---|
| send_commands.py | Run codes, evaluate expressions, read part of the object model, write messages, handle errors |
| subscribe_object_model.py | Filtered patch subscription, key callbacks with and without ^ |
| custom_m_codes.py | Custom M-codes, reading parameters, running codes from an interceptor |
| custom_http_endpoint.py | GET and POST endpoints with plain text and JSON responses |
Development
python3 -m pip install -e ".[dev]"
python3 -m pytest # Tests use mock DSF sockets, no DSF install needed
sphinx-build -b html docs/source docs/build # API reference
Metadata
Release files for dsf-python 3.7.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| dsf_python-3.7.0.tar.gz | 125.3 kB | With provenance | Details for dsf_python-3.7.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| dsf_python-3.7.0-py3-none-any.whl | Python 3 | none | any | Details for dsf_python-3.7.0-py3-none-any.whl |
Total release size: 271.1 kB
Release files / dsf_python-3.7.0.tar.gz
| Download URL | dsf_python-3.7.0.tar.gz |
|---|---|
| Size | 125.3 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
6d3e7d9a0b6ae00be530e19576edc3525c0c0a859d1a4f33e596332cd037caac
|
|
BLAKE2b-256 checksum How to use checksums |
33d2b960882f97111af05c4c5810cf9c0492cdabbf0eac05bf71871bf4559b3d
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 8, 2026.
Transparency logRelease files / dsf_python-3.7.0-py3-none-any.whl
| Download URL | dsf_python-3.7.0-py3-none-any.whl |
|---|---|
| Size | 145.8 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
5387b448413db161fe6bb54fc583d186947df6b3acd0f9b9954f4f5c60c155fb
|
|
BLAKE2b-256 checksum How to use checksums |
23ccaac603632b0bd6e207693115c294457e226bea6e0e6cf46230b1434c90ec
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 8, 2026.
Transparency logSecurity for dsf-python 3.7.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for dsf_python-3.7.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 8, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.