Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions docs/web/docs/TraCI/Interfacing_TraCI_from_Python.md
Original file line number Diff line number Diff line change
Expand Up @@ -349,6 +349,9 @@ Make sure that the TRACIPATH corresponds to the sumo version that you wish to us
If it does not, then the order of directories in LOADPATH (sys.path) must be changed
or the SUMO installation must be removed from any directories that come before the wanted directory.

Use `traci.getClientVersion()` to determine the protocol version of the Python client without connecting.
The Python client's `traci.start()` and `traci.init()` warn if the server reports a different protocol version.

### Debugging a TraCI session on Linux

Sometimes SUMO may crash while running a simulation with TraCI. The
Expand Down
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
tests/complex/traci/connection/client_version/runner.py
3 changes: 3 additions & 0 deletions tests/complex/traci/connection/client_version/output.complex
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Matching protocol versions have no warning
Differing protocol versions produce a warning at startup
A raised startup warning cleans up the new connection and process
73 changes: 73 additions & 0 deletions tests/complex/traci/connection/client_version/runner.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
#!/usr/bin/env python
# Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.dev/sumo
# Copyright (C) 2026 German Aerospace Center (DLR) and others.
# This program and the accompanying materials are made available under the
# terms of the Eclipse Public License 2.0 which is available at
# https://www.eclipse.org/legal/epl-2.0/
# This Source Code may also be made available under the following Secondary
# Licenses when the conditions for such availability set forth in the Eclipse
# Public License 2.0 are satisfied: GNU General Public License, version 2
# or later which is available at
# https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html
# SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later

# @file runner.py
# @author Mark Colley
# @date 2026-12-03

import os
import sys
import warnings

if "SUMO_HOME" in os.environ:
sys.path.append(os.path.join(os.environ["SUMO_HOME"], "tools"))
import sumolib # noqa
from traci import constants, main as client # noqa

cmd = [sumolib.checkBinary("sumo"), "-n", "input_net.net.xml", "--no-step-log",
"--no-duration-log"] + sys.argv[1:]

with warnings.catch_warnings(record=True) as matching:
warnings.simplefilter("always")
version = client.start(cmd, label="matching")
try:
assert client.getVersion() == version
assert not matching, matching
print("Matching protocol versions have no warning")

constants.TRACI_VERSION = version[0] - 1
with warnings.catch_warnings(record=True) as differing:
warnings.simplefilter("always")
actual = client.start(cmd, label="differing", doSwitch=False)
try:
assert actual == version
assert client.getLabel() == "matching"
assert len(differing) == 1, differing
message = str(differing[0].message)
assert str(constants.TRACI_VERSION) in message and str(version[0]) in message and version[1] in message
assert differing[0].filename == __file__, differing[0].filename
assert client.getClientVersion() == constants.TRACI_VERSION
print("Differing protocol versions produce a warning at startup")
finally:
client.getConnection("differing").close()

opened = []
client.setConnectHook(opened.append)
try:
with warnings.catch_warnings():
warnings.simplefilter("error", UserWarning)
try:
client.start(cmd, label="rejected")
except UserWarning:
pass
else:
client.getConnection("rejected").close()
raise AssertionError("Expected the startup warning to raise")
finally:
client.setConnectHook(None)
assert len(opened) == 1 and opened[0]._process.poll() is not None
assert not client.connection.has("rejected")
assert client.getLabel() == "matching"
print("A raised startup warning cleans up the new connection and process")
finally:
client.close()
3 changes: 3 additions & 0 deletions tests/complex/traci/connection/testsuite.complex
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,6 @@ tracing

# Python TraCI socket framing, partial I/O, and connection close recovery
transport_recovery

# Python TraCI version warnings during startup
client_version
3 changes: 3 additions & 0 deletions tools/traci/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,6 @@
else:
warnings.warn("Could not import libtraci, falling back to pure python traci (%s)." % e)
from .main import * # noqa

if 'getClientVersion' in globals():
__all__.append('getClientVersion')
31 changes: 29 additions & 2 deletions tools/traci/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,10 +113,29 @@ def init(port=8813, numRetries=tc.DEFAULT_NUM_RETRIES, host="localhost", label="
label. This method is not thread-safe. It accesses the connection
pool concurrently.
"""
return _init(port, numRetries, host, label, proc, doSwitch, traceFile, traceGetters)


def _init(port, numRetries, host, label, proc, doSwitch, traceFile, traceGetters):
con = connect(port, numRetries, host, proc, 1, traceFile, traceGetters, label)
version = con.getVersion()
clientVersion = getClientVersion()
if clientVersion != version[0]:
try:
warnings.warn("TraCI client protocol version %s differs from protocol version %s reported by %s."
% (clientVersion, version[0], version[1]), stacklevel=3)
except UserWarning:
try:
con.close(wait=False)
except (socket.error, FatalTraCIError, TraCIException):
# An incompatible server may reject the close command.
pass
if proc is not None:
proc.wait()
raise
if doSwitch:
switch(label)
return con.getVersion()
return version


def start(cmd, port=None, numRetries=tc.DEFAULT_NUM_RETRIES, label="default", verbose=False,
Expand Down Expand Up @@ -144,7 +163,7 @@ def start(cmd, port=None, numRetries=tc.DEFAULT_NUM_RETRIES, label="default", ve
print("Calling " + ' '.join(cmd2))
sumoProcess = subprocess.Popen(cmd2, stdout=stdout)
try:
result = init(sumoPort, numRetries, "localhost", label, sumoProcess, doSwitch, traceFile, traceGetters)
result = _init(sumoPort, numRetries, "localhost", label, sumoProcess, doSwitch, traceFile, traceGetters)
if traceFile is not None:
connection.get(label)._traceFile.write("import traci\n")
connection.get(label)._traceFile.write("traci.start(%s, port=%s, label=%s)\n" % (
Expand Down Expand Up @@ -237,6 +256,14 @@ def removeStepListener(listenerID):
return connection.check().removeStepListener(listenerID)


def getClientVersion():
"""getClientVersion() -> int

Returns the TraCI protocol version implemented by the Python client.
"""
return tc.TRACI_VERSION


def getVersion():
"""getVersion() -> tuple

Expand Down
Loading