Thin Python wrapper for running and monitoring
TRNSYS batch simulations. The package includes the
trnrun.exe runner and the
trnrund.exe
daemon.
Contents
- Requirements
- Installation
- Quick start
- Run a batch
SimulationSettingsSimulationManagerSimulationDaemon- Examples
Requirements
- Windows x64
- Python 3.12 or newer
- TRNSYS 17 or 18
- Optional: Type3830 Progress Tracker for progress and stall monitoring
Installation
Install with pip:
pip install trnrun
Or with uv:
uv add trnrun
Quick start
from trnrun import SimulationManager
with SimulationManager(workers=1) as manager:
simulation = manager.add(r"C:\path\to\deck.dck", watch_tmp=True)
manager.wait(simulation)
if simulation.succeeded:
print(f"Completed: {simulation.deck_file}")
else:
print(f"Failed: {simulation.deck_file}")
Run a batch
from pathlib import Path
from trnrun import SimulationManager
decks = sorted(Path(r"C:\path\to\decks").glob("*.dck"))
with SimulationManager(workers=4) as manager:
for deck in decks:
manager.add(deck, watch_tmp=True)
manager.wait()
succeeded = [sim for sim in manager.simulations.values() if sim.succeeded]
print(f"{len(succeeded)} succeeded, {len(decks) - len(succeeded)} failed")
SimulationSettings
SimulationSettings defines how one deck is launched and monitored. Each field
that is set becomes one
TRNRun Runner option;
a field left at None keeps the runner's default, listed below. trnrund checks
the values when the simulation is added.
add takes the fields either as a SimulationSettings or as keyword
arguments. Keyword arguments override the fields of a SimulationSettings
passed with them, and an unknown name raises TypeError:
from trnrun import SimulationSettings
settings = SimulationSettings(watch_tmp=True, poll_ms=10)
manager.add(deck, settings) # watch_tmp=True, poll_ms=10
manager.add(deck, watch_tmp=True) # the same as SimulationSettings(watch_tmp=True)
manager.add(deck, settings, poll_ms=20) # watch_tmp=True, poll_ms=20
Executable and window
-
trnexe_path(str | Path, default:C:\TRNSYS18\Exe\TrnEXE64.exe)Path to the
TrnEXE64.exeorTrnEXE.exeexecutable. A relative path resolves from Python's working directory; a missing file raisesFileNotFoundErrorbefore the simulation is queued. -
gui_visibility(str, default:"hidden")Controls the TRNSYS simulation window:
keep: show the window and leave it open after the simulation.auto: show the window and close it after the simulation.min: minimize the window and leave it open afterward.minAuto: minimize the window and close it afterward.hidden: hide the window and close it after the simulation.
Launch detection
-
wait_for_gui(bool, default:True)Wait for a recognized TRNSYS simulation window as part of the launch-readiness checks.
-
wait_for_lst(bool, default:True)Wait for the component-order header in the deck's
.lstfile. -
wait_for_tmp(bool, default:False)Wait for a Type3830
.tmpfile. Do not enable this for a deck without Type3830, or launch detection will wait until its deadline. -
detect_timeout_ms(int, default:300_000)Maximum time, in milliseconds, to wait for launch readiness. Set to
0to wait indefinitely. The runner holds the launch mutex for the current Windows session until detection completes. -
extra_delay_ms(int, default:0)Additional delay in milliseconds after all enabled readiness checks pass.
Runtime monitoring
-
poll_ms(int, default:100)Polling interval in milliseconds for the TRNSYS process and output files.
-
watch_log(bool, default:True)Read the deck's
.logfile and report its entries aslogs. -
watch_tmp(bool, default:False)Read Type3830
.tmpupdates and report the simulation period and progress. Required for progress-basedSimulationStatus.CANCELLEDandSimulationStatus.STALLEDoutcomes. Without Type3830 in the deck, an early exit is reported asDONE. -
watch_timeout_ms(int, default:0)Maximum runtime-monitoring duration in milliseconds.
0means unlimited. -
stall_timeout_ms(int, default:0)Maximum milliseconds without simulation-time progress.
0disables stall detection. Requireswatch_tmp=Trueand a valid Type3830 snapshot. -
kill_on_timeout(bool, default:False)Terminate the TRNSYS process when launch detection or runtime monitoring times out. If disabled, a detection timeout proceeds to runtime monitoring; after a runtime-monitoring timeout, the runner stops polling and waits for the process to exit.
-
kill_on_stall(bool, default:False)Terminate the TRNSYS process after detecting a stall. Without it, the runner waits for the process to exit.
Output and cleanup
-
clean_on_success(bool, default:False)Delete
.tmp,.log,.lst, and.PTIsidecar files after a successful run. -
severity(LogSeverity | str, default:"Notice")Minimum reported log severity:
Notice,Warning, orFatal. -
write_events(bool, default:False)Mirror the runner events to a
.jsonlfile beside the deck, replacing any existing file when the run starts.
A configuration with every field set explicitly:
from pathlib import Path
from trnrun import SimulationSettings
settings = SimulationSettings(
trnexe_path=Path(r"C:\TRNSYS18\Exe\TrnEXE64.exe"),
gui_visibility="hidden",
wait_for_gui=True,
wait_for_lst=True,
wait_for_tmp=True,
detect_timeout_ms=300_000,
extra_delay_ms=0,
poll_ms=100,
watch_log=True,
watch_tmp=True,
watch_timeout_ms=300_000,
stall_timeout_ms=300_000,
clean_on_success=True,
kill_on_timeout=True,
kill_on_stall=True,
severity="Notice",
write_events=False,
)
SimulationManager
SimulationManager owns one trnrund.exe and keeps a Simulation per run up
to date. Nothing runs in the background: simulations are refreshed, and the
display moves, while add or wait block, or when you call refresh().
Leaving the with block, or calling close(), kills every unfinished run.
Parameters
-
workers(int, default: logical processor count minus one, at least1)Maximum number of simulations running at once. Additional simulations wait in the queue.
-
display(bool, default:True)Show one live line per running simulation and print each finished one once, in the terminal or a Jupyter notebook.
-
poll_interval(float, default:0.1)Seconds between refreshes while
addorwaitblock. -
trnrund_path(str | Path, default: bundledtrnrund.exe)Path to the
trnrund.exeexecutable. -
trnrun_path(str | Path, default: bundledtrnrun.exe)Path to the
trnrun.exeexecutable.
An explicitly configured manager:
from pathlib import Path
from trnrun import SimulationManager
with SimulationManager(
workers=4,
display=True,
poll_interval=0.1,
trnrund_path=Path(r"C:\path\to\trnrund.exe"),
trnrun_path=Path(r"C:\path\to\trnrun.exe"),
) as manager:
...
Methods and properties
-
simulations(dict[int, Simulation])Every simulation added, by
sim_id. -
daemon(Daemon)The
Daemonthis manager owns, usable directly for other commands, such asmanager.daemon.request({...}). -
add(deck_file: str | Path, settings: SimulationSettings | None = None, *, label: str | None = None, wait_for: str | None = None, **options) -> SimulationQueue
deck_fileand return itsSimulation.settingsandoptionsare theSimulationSettings;labelis free text shown instead of the deck path.wait_forpicks how longaddblocks:wait_foraddreturnsNoneat once (default) "QUEUED"at once: trnrund has queued it before it answers "RUNNING"once it started, so the next one is added only then "FINISHED"once it finished: one at a time -
wait(*simulations: Simulation, until: str = "FINISHED", timeout: float | None = None) -> NoneBlock until the given simulations, by default every one added, reach
until. RaisesTimeoutErroraftertimeoutseconds. -
cancel(*simulations: Simulation) -> NoneStop queued or running simulations; finished ones are left unchanged. The next refresh shows them
FINISHEDwith statusCANCELLED. -
refresh() -> NoneUpdate every simulation once and redraw the display.
-
close() -> NoneStop
trnrund.exe, killing unfinished runs, and erase the live display.
Example manager workflow with every method and property:
from trnrun import SimulationManager
manager = SimulationManager(workers=2)
try:
first = manager.add(r"C:\path\to\first.dck", watch_tmp=True, wait_for="RUNNING")
second = manager.add(r"C:\path\to\second.dck", watch_tmp=True, label="second")
manager.wait(first)
print(f"First status: {first.status}")
manager.cancel(second)
manager.wait(timeout=60)
manager.refresh()
print(f"Simulations: {len(manager.simulations)}")
print(f"First succeeded: {first.succeeded}")
print(f"Second status: {second.status}")
finally:
manager.close()
Simulation
SimulationManager.add() returns a Simulation for one run, which the manager
updates in place on each refresh. A field is
None until the runner reports it.
Properties
-
sim_id(int)Identifier assigned by the daemon, never reused.
-
deck_file(Path)Absolute path to the submitted deck.
-
label(str | None)Label it was added with.
-
trnrun_options(dict[str, Any])Runner options it was added with, such as
{"watchTmp": True}. -
state(SimulationState)QUEUEDwhile waiting for a worker,RUNNINGonce the runner started, andFINISHEDonce it completed, failed, or was cancelled. -
is_finished(bool)Whether
stateisFINISHED;logsare then complete. -
status,status_message(SimulationStatus | None,str | None)Latest runner status and its detail.
-
succeeded(bool | None)Set once finished.
Trueonly with statusDONE, exit code0, and noerror. -
exit_code(int | None)Runner exit code;
Noneif it was cancelled or never started. -
error(str | None)Why the daemon failed or cancelled the run.
-
sim_time,percent,elapsed_ms,eta_ms(float | None)Latest Type3830 progress.
sim_timeis in simulated hours,percentis a fraction from0to1, andelapsed_msandeta_msare milliseconds. -
start_time,stop_time,time_step(float | None)Simulation period reported by Type3830, in simulated hours.
-
setting(dict | None)Settings the runner applied, its defaults included, keyed by the runner's camelCase names.
-
notices,warnings,fatals(int)Number of log entries so far, by severity.
-
logs(list[LogEvent])Log entries, oldest first; filled in once the simulation finishes.
-
submitted_at,started_at,finished_at(datetime | None)UTC times;
started_atstaysNonefor a simulation that never started.
An example inspecting every property:
from trnrun import SimulationManager
with SimulationManager(workers=1) as manager:
simulation = manager.add(r"C:\path\to\deck.dck", watch_tmp=True)
manager.wait(simulation)
print(f"ID: {simulation.sim_id}")
print(f"Deck: {simulation.deck_file}")
print(f"Label: {simulation.label}")
print(f"Runner options: {simulation.trnrun_options}")
print(f"State: {simulation.state}")
print(f"Finished: {simulation.is_finished}")
print(f"Status: {simulation.status} {simulation.status_message}")
print(f"Succeeded: {simulation.succeeded}")
print(f"Exit code: {simulation.exit_code}")
print(f"Error: {simulation.error}")
print(f"Progress: {simulation.percent} at {simulation.sim_time} h")
print(f"Elapsed: {simulation.elapsed_ms} ms, ETA: {simulation.eta_ms} ms")
print(f"Period: {simulation.start_time} to {simulation.stop_time} by {simulation.time_step} h")
print(f"Runner settings: {simulation.setting}")
print(f"Notices: {simulation.notices}")
print(f"Warnings: {simulation.warnings}")
print(f"Fatals: {simulation.fatals}")
print(f"Logs: {simulation.logs}")
print(f"Times: {simulation.submitted_at}, {simulation.started_at}, {simulation.finished_at}")
Daemon
Daemon is a thin client with one method per
trnrund command,
for applications that do their own polling. Its requests are thread-safe: they
take turns. It takes the workers, trnrund_path, and trnrun_path
parameters of SimulationManager.
Methods
-
add(deck_file: str | Path, settings: SimulationSettings | None = None, *, label: str | None = None, **options) -> intQueue
deck_fileand return itssim_id, as forSimulationManager.add. -
simulation(sim_id: int, *, with_logs: bool = False) -> SimulationReturn one simulation, without
logsunlesswith_logsisTrue. -
simulations(state: str, *, with_logs: bool = False) -> list[Simulation]Return every unreleased simulation in
state, oldest first. -
cancel(sim_id: int) -> NoneStop a queued or running simulation; one already finished is left unchanged.
-
release(sim_id: int) -> NoneForget a finished simulation and its logs.
-
request(request: dict) -> dictSend any raw trnrund request and return its raw response.
-
close() -> NoneStop
trnrund.exe, killing unfinished runs.
RequestError is raised when trnrund refuses a request, such as for a missing
deck, an unknown sim_id, or releasing an unfinished run, and
DaemonExitedError when it no longer answers. Both subclass TrnrunError.
Simulation outcomes do not raise: inspect each simulation's succeeded,
status, and exit_code instead.
Example daemon workflow with every method:
from time import sleep
from trnrun import Daemon, RequestError
daemon = Daemon(workers=2)
try:
first = daemon.add(r"C:\path\to\first.dck", watch_tmp=True)
second = daemon.add(r"C:\path\to\second.dck", watch_tmp=True, label="second")
print(daemon.simulation(first))
print(f"Running: {len(daemon.simulations('RUNNING'))}")
daemon.cancel(second)
while not daemon.simulation(second).is_finished:
sleep(0.1)
cancelled = daemon.simulation(second, with_logs=True)
print(f"Second status: {cancelled.status}, {len(cancelled.logs)} log entries")
daemon.release(second)
try:
daemon.release(first)
except RequestError as error:
print(f"First not finished: {error}")
raw = daemon.request({"cmd": "simulations", "state": "RUNNING"})
print(f"Raw response: {raw}")
finally:
daemon.close()
Examples
Runnable examples are available in the TRNRun repository.
Metadata
Release files for trnrun 0.9.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| trnrun-0.9.1-py3-none-win_amd64.whl | Python 3 | none | Windows x86-64 | Details for trnrun-0.9.1-py3-none-win_amd64.whl |
Release files / trnrun-0.9.1-py3-none-win_amd64.whl
| Download URL | trnrun-0.9.1-py3-none-win_amd64.whl |
|---|---|
| Size | 506.5 kB |
| Tags | Python 3 Windows x86-64 |
|
SHA-256 checksum How to use checksums |
6f6f8d100f4e82ed8d30c047b04809e67e5084d6eeda0838aac4a652d43baf06
|
|
BLAKE2b-256 checksum How to use checksums |
4cfd6263fcca427c9cee0ac540a9f8a9c42a3a3ce020dd85196b8ed24bda721e
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.14.2
|
Security for trnrun 0.9.1
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.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A 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.