Python#
This guide describes how to install the Python client, and the features it provides. The Client API Reference describes each function and class.
Installing the Library#
The library can be found on PyPI or downloaded from GitHub.
To install using pip:
pip install krpc
Connecting to the Server#
The game must be running with the server started. The Server Plugin in the getting started guide shows how to install and start it.
The client connects over TCP/IP or over a local socket. Each server in the server window uses one protocol, and accepts connections over that protocol only. Pick the protocol when you add the server, and connect with the matching function.
Note
A server with “Auto-accept new clients” turned off answers only once the player approves the
connection in game. The connection fails after 5 seconds by default. Pass
handshake_timeout=None to wait indefinitely for the player.
Over TCP/IP#
Select “Protobuf over TCP/IP” as the server’s protocol. connect() connects to it, and
returns a krpc.Connection. You make every call through this object. The following
connects to a server with the default settings, address 127.0.0.1 and port 50000, and prints
its version:
import krpc
conn = krpc.connect()
print(conn.krpc.get_status().version)
connect() also takes the address and port of the server, and a name for the connection.
These match the address and port shown in the server window. The name appears in the server window
in the game:
import krpc
conn = krpc.connect(
name="My Example Program", address="192.168.1.10", port=1000
)
print(conn.krpc.get_status().version)
TCP/IP works over a network, so your program can run on a different machine from the game.
Over a Local Socket#
Select “Protobuf over local socket” as the server’s protocol. connect_local() connects
to it, and returns a krpc.Connection as connect() does. The following
connects to a server with the default settings, at the default socket path for your platform, and
prints its version:
import krpc
conn = krpc.connect_local(name="My Example Program")
print(conn.krpc.get_status().version)
connect_local() also takes a path, for a server with another socket path. The path
matches the one shown in the server window.
A local socket works only on the machine running the game. It has lower overhead than TCP/IP, so it is faster.
Closing the Connection#
Use the connection in a with statement to close it at the end of the block:
import krpc
with krpc.connect(name="My Example Program") as conn:
print(conn.krpc.get_status().version)
close() closes a connection explicitly. A connection you do not close stays
open until your program exits, even when your program no longer holds it.
Calling Remote Procedures#
The server provides procedures for your program to call, grouped into services.
The following gets the active vessel from SpaceCenter.active_vessel, an object of type
SpaceCenter.Vessel. It sets the vessel’s name, then prints its altitude:
import krpc
conn = krpc.connect()
vessel = conn.space_center.active_vessel
vessel.name = "My Vessel"
flight_info = vessel.flight()
print(flight_info.mean_altitude)
Each service is an attribute of the connection, such as conn.space_center for the
SpaceCenter service. From an interactive terminal, help(conn.space_center) lists the
classes, enumerations, procedures and properties of the service. help(conn.space_center.Vessel)
does the same for a class.
Handling Errors#
A procedure that fails on the server raises an exception in your program. The following catches the error from loading a save that does not exist:
import krpc
conn = krpc.connect()
try:
conn.space_center.load("missing")
except ValueError as error:
print("Failed to load the save:", error)
The exception you catch depends on the error:
A standard error, such as an invalid argument, raises a class whose only base is the matching Python exception. The example catches
ValueError, as a missing save raisesconn.krpc.ArgumentException.An error particular to a service raises a class of that service, such as
conn.krpc.ObjectDestroyedException, derived fromkrpc.error.ServerError.An error the client has no class for raises
krpc.error.ServerError.A call made once the connection has closed or failed raises
krpc.error.ConnectionError.An argument the client rejects before sending the call raises
ValueErrororTypeError.
Every error of the client’s own derives krpc.error.RemoteError. A standard error, such as
conn.krpc.ArgumentException, does not.
Values#
Procedures take and return Python values, such as int, str, list and dict, and
None for a null. The services also define their own types:
A class is a remote object, described below.
A structure is a
NamedTuple.An enumeration is an
enum.Enum, or anenum.Flagfor a flags enumeration.
Flags Enumerations#
A flags enumeration, such as SpaceCenter.MapFilterType, holds any combination of its
values. It is an enum.Flag. You combine values with |, and test for one with in:
import krpc
conn = krpc.connect()
space_center = conn.space_center
MapFilterType = space_center.MapFilterType
# Show only probes and ships in map mode
space_center.map_filter = MapFilterType.probes | MapFilterType.ships
# Check whether map mode shows debris
print(MapFilterType.debris in space_center.map_filter)
# Show debris as well
space_center.map_filter |= MapFilterType.debris
&, ^ and ~ give the other combinations. ~ keeps to the values the enumeration
declares.
Remote Objects#
Many procedures return an object identifying something in the game, such as a vessel or a part. The object holds no copy of the game’s state. It is just a reference to it. Each call through it reads the game as it is now:
import time
import krpc
conn = krpc.connect()
vessel = conn.space_center.active_vessel
flight_info = vessel.flight()
# Each read gets the current altitude from the game
print(flight_info.mean_altitude)
time.sleep(1)
print(flight_info.mean_altitude)
# Two objects for the same vessel are equal
print(vessel == conn.space_center.active_vessel)
Two objects for the same thing in the game compare equal, and can be used as dictionary keys.
Once the thing an object identifies is destroyed, such as a part that explodes, each call through
it raises conn.krpc.ObjectDestroyedException.
An object for a vessel or a part keeps working when you load a save, quickload or revert, and then reads the loaded game. Other objects depend on what they identify. A maneuver node, for example, is destroyed by a load.
A vessel far from the active vessel is unloaded, and the game keeps no parts for it. The vessel
itself reads normally, but a call on one of its parts raises
conn.krpc.ObjectNotLoadedException. The part works again once the vessel comes back into
range.
See also
Object Lifetime describes how each kind of object behaves in more detail.
Calling Methods#
You call a method on an object of its class. A static method needs no object, and you call it on
the class itself. Reach the class through the connection’s service. Pass the method to
add_stream() to stream it:
import krpc
conn = krpc.connect()
vessel = conn.space_center.active_vessel
frame = vessel.orbit.body.reference_frame
Orbit = conn.space_center.Orbit
# Call a method on an object
print(vessel.position(frame))
# Call a static method on the class
print(Orbit.reference_plane_direction(frame))
# Stream it
direction = conn.add_stream(Orbit.reference_plane_direction, frame)
print(direction())
The call runs on the connection the class is reached through. Called through an object, a static method runs on the object’s connection.
Streaming Data#
A common use of kRPC is to read data from the game continuously. The following does so by calling a remote procedure in a loop, printing the position of the active vessel:
import krpc
conn = krpc.connect()
vessel = conn.space_center.active_vessel
refframe = vessel.orbit.body.reference_frame
while True:
print(vessel.position(refframe))
Each call sends a request to the server and waits for its response. A stream is more efficient. The server runs the call repeatedly, and sends your program the result each time it changes.
The following does the same as above using a stream:
import krpc
conn = krpc.connect()
vessel = conn.space_center.active_vessel
refframe = vessel.orbit.body.reference_frame
position = conn.add_stream(vessel.position, refframe)
while True:
print(position())
add_stream() creates the stream from the method and its arguments, and
returns a krpc.stream.Stream. Calling it returns the stream’s latest value.
A property is streamed with getattr and the property’s name:
import krpc
conn = krpc.connect()
vessel = conn.space_center.active_vessel
flight_info = vessel.flight()
altitude = conn.add_stream(getattr, flight_info, "mean_altitude")
while True:
print(altitude())
Each call to add_stream() creates another stream. A stream of a
procedure with no return value, or of a property setter passed with setattr, runs the call on
each update for its effects. Its value is None.
A stream runs until you remove it with remove(), or the connection
closes. It keeps running after your program drops its last reference to it, so remove a stream you
no longer need. A with statement removes a stream at the end of the block:
import krpc
conn = krpc.connect()
vessel = conn.space_center.active_vessel
refframe = vessel.orbit.body.reference_frame
with conn.add_stream(vessel.position, refframe) as position:
while True:
print(position())
By default, the server sends a stream’s value each time it changes. Set
rate to limit how many times a second the stream updates:
import krpc
conn = krpc.connect()
vessel = conn.space_center.active_vessel
flight_info = vessel.flight()
altitude = conn.add_stream(getattr, flight_info, "mean_altitude")
# Update the stream at most 10 times a second
altitude.rate = 10
Waiting for Changes#
Each stream has a condition variable, a threading.Condition from the Python standard library.
wait() blocks until the stream’s value changes. The following waits for
the abort button to be pressed:
import krpc
conn = krpc.connect()
vessel = conn.space_center.active_vessel
with conn.add_stream(getattr, vessel.control, "abort") as abort:
with abort.condition:
while not abort():
abort.wait()
Hold the condition when you call wait(), as the with statement does
here. While you hold it, the value changes only when you wait, so the loop misses no updates. An
ending reaches you the same way: the wait returns, and your next read or wait raises the exception
that ended the stream.
wait() takes a timeout in seconds, and returns False when it elapses
before an update.
Callbacks#
A callback is a function the client calls with each new value of a stream. The following adds two callbacks to a stream of the abort button:
import time
import krpc
conn = krpc.connect()
vessel = conn.space_center.active_vessel
abort = conn.add_stream(getattr, vessel.control, "abort")
def check_abort1(x):
print("Abort 1 called with a value of", x)
def check_abort2(x):
print("Abort 2 called with a value of", x)
abort.add_callback(check_abort1)
abort.add_callback(check_abort2)
# Keep the program running, while the callbacks are called
while True:
time.sleep(1)
A callback added to a stream that already has a value is called with that value straight away. It is then called with each new value, in order.
Note
Each connection has a callback thread, which runs the callbacks of its streams one at a time. A callback can make remote procedure calls. Other callbacks and waits are held up while it runs, so return promptly, and do not wait on a stream in a callback. For a long running task, start a worker thread from the callback.
Stream Endings#
A stream ends when its procedure raises an exception, when the server removes it, when you remove it, or when the connection closes. Calling the stream or waiting on it then raises the exception that ended it. The following streams the temperature of a part until the part is destroyed:
import krpc
conn = krpc.connect()
vessel = conn.space_center.active_vessel
temperature = conn.add_stream(getattr, vessel.parts.root, "temperature")
try:
with temperature.condition:
while True:
temperature.wait()
print("Temperature", temperature())
except conn.krpc.ObjectDestroyedException:
print("The part was destroyed")
The exception is the one the procedure raised, or one of the following:
krpc.error.StreamErrorwhen you or the server remove the stream, such as for an event that has finished.krpc.error.ConnectionErrorwhen the connection closes or fails.
An exception for an object that is not loaded, or for a procedure not available in the current game scene, does not end the stream. It pauses the stream’s updates, and the stream keeps its last value. The updates resume once the object or the scene is available.
See also
Object Lifetime describes when each kind of object is not loaded, and how streams behave around a load.
add_end_callback() adds a callback that is called once when the stream
ends, with the exception. The following prints the temperature of a part with a callback, and
prints the exception when the stream ends:
import time
import krpc
conn = krpc.connect()
vessel = conn.space_center.active_vessel
temperature = conn.add_stream(getattr, vessel.parts.root, "temperature")
def print_temperature(value):
print("Temperature", value)
def print_ending(error):
print("The stream ended:", error)
temperature.add_callback(print_temperature)
temperature.add_end_callback(print_ending)
# Keep the program running, while the callbacks are called
while True:
time.sleep(1)
Server Side Functions#
A server side function is a Python function or lambda in your script that runs inside the game. The client compiles it and sends it to the server, which runs it there. The following reads the vessel’s altitude and speed together:
import krpc
conn = krpc.connect()
vessel = conn.space_center.active_vessel
flight = vessel.flight(vessel.orbit.body.reference_frame)
# Run the lambda on the server, so both values come from the same physics
# tick
altitude, speed = conn.run(lambda: (flight.mean_altitude, flight.speed))
print("Altitude:", altitude, "m, speed:", speed, "m/s")
Writing Server Side Functions describes what a function can contain. The server side functions guide shows how to build larger functions.
Running a Function#
run() runs a function once, and returns its value. The server runs the
whole function within one physics tick, so every value it reads comes from the same moment in the
game. In the example, the altitude and the speed are consistent with each other, which two
separate calls cannot guarantee.
Streaming a Function#
Pass a function to add_stream() to stream its value. The server
evaluates the function on each update, within one physics tick. The following streams the
vessel’s altitude in kilometers:
import time
import krpc
conn = krpc.connect()
vessel = conn.space_center.active_vessel
flight = vessel.flight()
# Stream the vessel's altitude in kilometers, computed on the server
stream = conn.add_stream(lambda: flight.mean_altitude / 1000)
while True:
print("Altitude:", stream(), "km")
time.sleep(1)
A function stream ends on an exception its function raises, just like an
ordinary stream. Unlike an ordinary stream, it also ends on
ObjectNotLoadedException from the KRPC service, raised while the game loads or when a vessel
unloads. The server cannot pause a function partway through, and running it again would repeat
its effects. To keep a function running through a load, catch the exception in the function:
def altitude_km():
try:
return flight.mean_altitude / 1000
except conn.krpc.ObjectNotLoadedException:
return 0.0
stream = conn.add_stream(altitude_km)
Events#
A common use of kRPC is to wait for something to happen in the game, such as the vessel reaching an altitude. An event does this efficiently. The server checks a condition, written as a server side function, and tells your program when it becomes true. The following waits until the vessel’s altitude exceeds 1000 meters:
import krpc
conn = krpc.connect()
vessel = conn.space_center.active_vessel
flight = vessel.flight()
# Create an event that triggers when the lambda returns true
event = conn.add_event(lambda: flight.mean_altitude > 1000)
# Wait on the event
with event.condition:
event.wait()
print("Altitude reached 1000m")
add_event() creates the event, and wait() waits
for it to fire. The server checks the condition every physics tick, so the event catches a
condition that holds for only a moment, which a loop of calls can miss.
The event fires again each time the condition becomes true after being false. Call
remove() to stop it. A with statement removes an event at the end of
the block:
import krpc
conn = krpc.connect()
flight = conn.space_center.active_vessel.flight()
expr = conn.krpc.Expression.greater_than(
conn.krpc.Expression.call(
conn.get_call(getattr, flight, "mean_altitude")
),
conn.krpc.Expression.constant_double(1000),
)
with conn.add_event(expr) as event:
with event.condition:
event.wait()
print("Altitude reached 1000m")
# The event was removed at the end of the block
As with a stream, hold the event’s condition when you call wait(). A wait
returns straight away if the event has fired since your last wait, so a firing between two waits is
not missed.
Event Callbacks#
An event can also call a callback each time it fires. The callback takes no arguments:
import time
import krpc
conn = krpc.connect()
vessel = conn.space_center.active_vessel
flight = vessel.flight()
event = conn.add_event(lambda: flight.mean_altitude > 1000)
def reached():
print("Altitude reached 1000m")
event.add_callback(reached)
# Keep the program running, while the callback is called
while True:
time.sleep(1)
Callbacks for events run on the connection’s callback thread, as the callbacks of a stream do.
Event Endings#
An event ends in the same ways as a stream. Waiting on an event that has ended raises the exception that ended it.
When the event fires just before the server ends it, your next wait returns for that firing first. Removing the event or closing the connection ends it at once.
add_end_callback() adds a callback that is called once when the event ends,
with the exception, just like an ordinary stream.
Threading#
A connection can be shared between threads. Each thread makes calls over it as it would alone, and each call returns its own result. The following prints the altitude and speed of the vessel from two threads:
import threading
import krpc
conn = krpc.connect()
vessel = conn.space_center.active_vessel
flight_info = vessel.flight(vessel.orbit.body.reference_frame)
def print_altitude():
for _ in range(10):
print("Altitude:", flight_info.mean_altitude)
def print_speed():
for _ in range(10):
print("Speed:", flight_info.speed)
# Both threads make calls over the same connection
threads = [
threading.Thread(target=print_altitude),
threading.Thread(target=print_speed),
]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
Streams and events can also be used from any thread:
Several threads can read a stream, or wait on a stream or an event. A change wakes every thread waiting for it.
A thread holding a stream’s condition does not stop other threads from making calls.
Callbacks run on the connection’s callback thread, one at a time, and never on your program’s threads. A callback added to a stream that already has a value is different. Its first call, with that value, might run on your thread, before
add_callback()returns. Protect state that a callback shares with your program’s threads, such as with athreading.Lock.
When one thread closes the connection, or the connection fails, the calls and waits of the other
threads end with krpc.error.ConnectionError. A wait on a stream or an event that another
thread removes ends with the exception for a removed stream.
Deprecated Members#
A member of a service can be deprecated, when a newer member replaces it. A deprecated member still works, but may be removed in a future release, so move to its replacement.
The API reference and the member’s docstring mark it as deprecated, and name the replacement.
Using it emits a DeprecationWarning naming the replacement too. Python shows a
DeprecationWarning by default only for code in __main__. Run Python with -W default, or
use the warnings module, to see the others.
The generated modules mark it with the @deprecated decorator of
PEP 702, so a type checker reports it too.
Writing Server Side Functions#
The client includes a compiler, which converts a Python function or lambda into a server side
function automatically when you pass it to run(),
add_stream() or add_event(). This section
describes what a function can contain, and how to compile one ahead of time.
Remote Calls and Constants#
The compiler translates the function’s source code into a server side function that computes the same result on the server, inside the game. Each part of the function either runs on the server or becomes a constant:
Attribute accesses and method calls on remote objects and services become calls in the function, made again on each evaluation. This includes calls on the elements of a collection in a comprehension. The procedures of the
KRPCservice cannot be called. They build and run server side functions and add streams, which a function would repeat on every evaluation.Reading an attribute of a structure a service defines reads that field of it on the server. Calling the structure type builds one there, with its field values given by position, by field name, or both.
Captured variables, literals and any sub-expression that makes no remote call are evaluated once, when the function is compiled, and embedded as constants. A client side function called there is a compile error if it makes a remote procedure call, as the call would run only once, when compiling. To use a value read once, read it before the function and capture the variable.
The compiler raises krpc.error.CompilationError for code that would run only once,
when compiling, where you would expect it to run on every evaluation:
Reading a stream inside a function, as the stream would be read once.
A call to a client side function written as a statement, such as
time.sleep(1). The builtins under Builtin Functions and Methods, such asprint, run on the server instead.A Python function passed to
add_event()oradd_stream()that makes no remote procedure call and uses no state variable, as its value is the same on every update. A function compiled withcompile()first is not checked.
Operators#
Operators, conditional expressions (
a if condition else b), indexing, slices without a step, f-strings without format specifiers,in,is Noneandis not Nonecompile to the matching expression operators./is true division,//is floor division, and the result of%takes the sign of the divisor, as in Python.andandorshort-circuit on the server, and produce the operand that decides the result.&and|evaluate both operands.+adds numbers, and concatenates two strings or two lists. The other arithmetic operators and the ordering comparisons take numbers only.==,!=andintake values of the same kind. Numbers of different types widen to a common type.
A function combines and tests the values of a flags enumeration
with |, &, ^, ~ and in:
import krpc
conn = krpc.connect()
space_center = conn.space_center
MapFilterType = space_center.MapFilterType
# Stream whether map mode shows both probes and ships, computed on the
# server
craft = MapFilterType.probes | MapFilterType.ships
shows_craft = conn.add_stream(lambda: craft in space_center.map_filter)
print(shows_craft())
Both operands are values of one flags enumeration.
None and Truth#
Nonetakes its type from where it is used: a parameter, the other branch of a conditional, the other elements of a list, the function’s other returns, or the variable’s other assignments. Elsewhere, give it a type with an annotation ortyping.cast, for examplecast(Optional[str], None).A condition tests truth as Python does.
Noneis false, a number is true when it is not zero, and a string, bytes or a collection when it is not empty. A flags value is true when it holds a flag. Any other value is true.
Collections#
Tuple, list, set and dictionary displays compile to the matching expression operators.
Comprehensions compile to the server’s collection operations, including dictionary comprehensions and several
forclauses with conditions.A comprehension target can unpack a tuple, as in
[key for key, value in d.items()].Iterating over a dictionary iterates over its keys, and
intests its keys.d.items()gives its key and value pairs,d.keys()its keys andd.values()its values.A string cannot be iterated over.
Builtin Functions and Methods#
The builtin functions
len,sum,any,all,reversed,abs,round,int,float,str,range,enumerateandzipof two collections compile to server side operations.sorted,minandmaxtake an optionalkeylambda.minandmaxtake a collection or several values, which are numbers unless akeyis given.sortedalso orders strings and tuples.The string methods
upper,lower,strip,lstrip,rstrip,replace,split,find,startswith,endswithandjoincompile to server side operations.strip,lstripandrstriptake no argument, andsplittakes a separator.A
mathmodule function with server side arguments compiles to aStdLibprocedure.printwrites a line to the game’s log withStdLib.print(). An argument computed on the server is a string, a number or a bool. A constant argument is formatted on the client, asstr()formats it.sepis a constant.
Statements#
A Python function can also contain statements, which run on the server. This one shuts down the engines that have run out of fuel, and returns how many it shut down:
import krpc
conn = krpc.connect()
vessel = conn.space_center.active_vessel
def shut_down_empty_engines() -> int:
count = 0
for engine in vessel.parts.engines:
if engine.active and not engine.has_fuel:
engine.active = False
count += 1
return count
# The function runs on the server, within a single physics tick
print(conn.run(shut_down_empty_engines), "engines shut down")
A function body can contain:
if,elifandelse,whileandforloops withbreakandcontinue, and early returns.Local variables, and assignment expressions (
:=).Assignment to the properties of remote objects and services.
Remote calls written as statements, for their effects.
Assignment that unpacks a tuple, as in
a, b = b, a, and afortarget that does.+=and the other augmented assignments.+=on a list extends it in place.Assignment to a list or dictionary element.
appendon a list andaddon a set.delof a list index or a dictionary key,removeon a list or a set,discardon a set, andclearon any collection.Local function definitions with annotated parameter types, and lambdas without parameters assigned to names. Calls to them run on the server.
raise, andtrywithexceptandfinallyclauses.match, with literal, value, capture, wildcard,|andaspatterns, and guards.
A function that returns a value must end with a return or raise statement, an if,
match or try that returns or raises on every path, or a while True loop with no
break. A match covers every path when its last case is _ or a capture, with no
guard.
This stream gives a description of where the vessel is, with a match on its situation:
import krpc
conn = krpc.connect()
vessel = conn.space_center.active_vessel
VesselSituation = conn.space_center.VesselSituation
def where() -> str:
match vessel.situation:
case (
VesselSituation.pre_launch
| VesselSituation.landed
| VesselSituation.splashed
):
return "on the surface"
case VesselSituation.orbiting | VesselSituation.escaping:
return "in space"
case _ if vessel.flight().mean_altitude < 1000:
return "near the ground"
case _:
return "in flight"
with conn.add_stream(where) as situation:
print("The vessel is", situation())
Variables and Types#
A variable takes its type from its first assignment. Annotate an assignment of an empty collection, for example
result: list[int] = []. An empty collection passed as an argument, or used beside a typed value, takes that type.An annotation names
int,float,boolorstr, alist,set,dictortupleof types, or a class, enumeration or structure a service defines.typing.cast(T, value)converts the value toTon the server. A float cast tointis truncated toward zero, where assigning it to anintvariable is an error.A variable assigned
Nonecan holdNone. A variable holding a string, an object or a collection can also beNonewhen a value assigned to it can.An annotation such as
Optional[int]orint | NoneallowsNonefor any type. AssigningNoneto a variable or a parameter annotated with a type that does not allow it is an error.A
Nonereaching a variable, a parameter or a set that does not take one raises an error when the function runs.A captured collection is copied to the server, so assigning to or deleting one of its elements is an error.
Scope#
A name assigned anywhere in the function is local to all of it, as in Python.
Reading a variable is an error unless every path to the read assigns it first. An assignment in a loop or a
trybody does not count after the loop or thetry. A capture in amatchcase with a guard does not count in the cases after it.A local function reads a variable when it is called, so the variable can be assigned after the function’s definition, if every path to each call assigns it.
A local function defined or redefined in a nested block can only be called within that block.
State Variables#
A captured variable declared nonlocal in the function is a state variable, which keeps its
value from one evaluation to the next. This stream gives the highest altitude the vessel has
reached:
def highest_altitude():
highest = 0.0
def update() -> float:
nonlocal highest
highest = max(highest, flight_info.mean_altitude)
return highest
return update
stream = conn.add_stream(highest_altitude())
State variables follow these rules:
It starts with the value it holds when the function is compiled. A compiled function keeps its value between runs, as does a stream or an event.
The value belongs to the compiled function, so two streams of one function advance it twice per update. A function compiled again on each call starts it again.
A local function cannot declare one.
Its type comes from its starting value. To give it another type, cast it in a statement of the function’s body before any other use of it, for example
values = cast(List[int], values)for a list that starts empty, orlast = cast(Optional[float], last)for a value that starts asNone.
Exceptions#
Exceptions map to the exceptions the server raises:
raisetakes an exception a service declares, or one of the builtins below.An exception a service declares is named by its class, such as
conn.krpc.ObjectNotLoadedException.RuntimeErrorstands forKRPC.InvalidOperationException.ValueErrorstands for the three argument exceptions.TypeError,KeyError,IndexError,ZeroDivisionError,NotImplementedError,TimeoutErrorandOverflowErrorstand for the matching kRPC exceptions.raise Exceptionraises aKRPC.Error, with the messagestr()gives its argument.An
exceptclause naming a base class, such asLookupError, catches the exceptions derived from it.except RuntimeErrorcatches every other exception the services declare, apart fromKRPC.Error.An
exceptclause can name a tuple of exceptions. Itsasname holds the exception’s message.except Exception, a bareexceptand a tuple namingExceptioncatch every exception.A
break,continueorreturncannot leave afinallyclause.
Differences from Python#
Some results differ from Python’s, as the server computes with fixed size numbers and its own collection operations:
Integer arithmetic wraps around on overflow.
A 32-bit unsigned integer a procedure returns is negated, or inverted with
~, as a 64-bit signed integer, so the result is negative as in Python. A 64-bit unsigned integer cannot be negated or inverted.A float passed where an integer is expected is an error. Convert it with
int().int(),round(),math.floorandmath.ceilof a float give a 32-bit integer.A float divided by zero gives
infornan.sumadds floats in order, where Python 3.12 and later compensates for rounding. For example,sum([0.1] * 10)gives0.9999999999999999.A math function outside its domain gives
nanorinfwhere Python raises an error. For example,math.sqrt(-1)givesnanandmath.log(0)gives-inf.A generator expression is computed in full where it is written.
anyandallstop early only over a generator expression written as their argument.sum,minandmaxskip aNoneamong the values, andsortedputs it first. Python raisesTypeErrorfor each.A negative index counts from the end only when it is a constant. A negative power of an integer is a fraction only when the power is a constant. A slice bound cannot be a negative constant.
The keys of a dictionary are integers, strings or
boolvalues.Bytes cannot be indexed, measured with
lenor searched within.str()and an f-string take a string, a number or a bool. A float uses the server’s formatting, so1.0becomes1.
Unsupported Constructs#
A construct with no server side equivalent raises krpc.error.CompilationError
naming it. Examples are a format specifier, str.format, and a call to a client side function
with server side arguments.
Compiling Ahead of Time#
Pass a Python function or lambda to compile() to compile it into a server
side function. add_event(), add_stream() and
run() take the result, and run it without compiling it again. The
following compiles a function once, and runs it every second:
import time
import krpc
conn = krpc.connect()
resources = conn.space_center.active_vessel.resources
# Compile the function once. Its remote procedure calls
# are made again each time the function runs
fuel_fraction = conn.compile(
lambda: resources.amount("LiquidFuel") / resources.max("LiquidFuel")
)
# Run the compiled function as often as needed
while True:
print("Fuel:", conn.run(fuel_fraction))
time.sleep(1)
Given a Python function or lambda, add_event(),
add_stream() and run() compile it again on every
call, so its captured variables take their current values. A compiled function keeps the values from
when it was compiled. Compiling makes a remote procedure call per node.
To use a function repeatedly, compile it once with compile() and pass the
result. compile() also compiles the function on the server, so its first
run is as fast as later ones.
compile() also works as a decorator, which replaces the function with
its compiled form:
@conn.compile
def altitude_km():
return flight.mean_altitude / 1000
stream = conn.add_stream(altitude_km)
Parameters#
A def can take parameters, each with a type annotation. run() passes
its arguments to them, with defaults and keyword arguments as in Python:
@conn.compile
def altitude_above(height: float, scale: float = 1000) -> float:
return (flight.mean_altitude - height) / scale
print(conn.run(altitude_above, 70000))
print(conn.run(altitude_above, 70000, scale=1))
Only a def takes parameters. An event or a function stream runs its function with no arguments.
Passing add_event() or add_stream() a def
with parameters raises krpc.error.CompilationError, and a compiled function with
parameters raises ValueError.
Type Checking#
krpc.connect() returns a krpc.ksp.KSPConnection, which declares every service the client
ships with for Kerbal Space Program, including krpc. A type checker then knows the type of each
member:
import krpc
conn = krpc.connect()
vessel = conn.space_center.active_vessel # Vessel | None
The client builds each service from the definitions the server sends when you connect, so it has
the procedures of that server. krpc.connect[T](...) connects with the connection type T in
place of KSPConnection.
Each service’s module, such as krpc.ksp.spacecenter, declares a connection type with only that
service, such as SpaceCenterConnection. A function can take the connection type of the services
it uses:
from krpc.ksp.spacecenter import SpaceCenterConnection
def stage(conn: SpaceCenterConnection) -> None:
vessel = conn.space_center.active_vessel
if vessel is not None:
vessel.control.activate_next_stage()
An enumeration, structure or exception from a module works with no connection:
from krpc.ksp.spacecenter import SASMode, Vessel
def set_sas_mode(vessel: Vessel, mode: SASMode = SASMode.prograde) -> None:
vessel.auto_pilot.sas_mode = mode
A class or service in a module is a declaration for type checkers. Use it in annotations and with
isinstance, and call it through a connection, such as
conn.space_center.ReferenceFrame.create_relative. Calling a declaration raises a TypeError.
The modules come from one kRPC release, and a server of another release is not supported. The services match the server, and the type hints are those of the client’s release. An enumeration or structure the server defines differently is built for the connection. A module’s enumeration value is sent by its number.
Services of Other Mods#
A service another mod adds is built when you connect, like the others. For type hints, generate a module for the service with krpc-clientgen, and combine its client type with the others you use:
import krpc
from krpc.ksp import KSPConnection
from mymod_services import MyModConnection
class MyConnection(KSPConnection, MyModConnection):
pass
conn = krpc.connect[MyConnection]()
conn.my_mod.get_mode()
A module generated for a newer server replaces the shipped module of the same service. Combine its
connection type with those of the other services you use, as it cannot combine with
KSPConnection, which has the shipped one:
from krpc.ksp.spacecenter import SpaceCenterConnection
from newer_services.ui import UIConnection
class MyConnection(UIConnection, SpaceCenterConnection):
pass
A client uses the enumerations, structures and exceptions of the modules its connection type names, where the server’s definitions match them. For a service its connection type does not name, it uses those of the module imported last.
Client API Reference#
- krpc.connect([name=None][, address='127.0.0.1'][, port=50000][, timeout=None][, handshake_timeout=5][, stall_timeout=30])#
Connects to a kRPC server, and returns a
krpc.ksp.KSPConnection.krpc.connect[T](...)returns a connection of the connection typeT, as in Type Checking.- Parameters:
name (str) – A name for the connection, shown in the server window in the game.
address (str) – The address of the server, as a host name or an IP address. Defaults to
'127.0.0.1'.port (int) – The port of the server. Defaults to 50000.
timeout (float) – How many seconds to wait for the connection to open. Defaults to
None, which waits indefinitely. Without a timeout, a network that drops the connection attempt leaves the client waiting.handshake_timeout (float) – How many seconds to wait for the server to accept the connection. Defaults to 5.
Nonewaits indefinitely, such as for a server that asks the player to approve each connection.stall_timeout (float) – How many seconds a message from the server can go without a new byte, once it has started to arrive, before the connection fails. Defaults to 30.
Nonewaits indefinitely.
Raises
krpc.error.ConnectionErrorif the connection fails or the server refuses it, andValueErrorfor a timeout that is not positive.
- krpc.connect_local([name=None][, path][, handshake_timeout=5][, stall_timeout=30])#
Connects to a kRPC server on the same machine over a local socket, and returns a
krpc.ksp.KSPConnection. The server must use the local socket protocol.krpc.connect_local[T](...)returns a connection of typeT, as forkrpc.connect().A script that makes many calls in quick succession completes more of them per physics update than over TCP/IP. A script that makes a call and then waits runs at the game’s update rate either way.
Local sockets are available on Linux, macOS, and Windows 10 1803 and Windows Server 2019 or later.
- Parameters:
name (str) – A name for the connection, shown in the server window in the game.
path (str) – The path of the server’s socket, shown in the server window in the game. Defaults to the path the server uses unless it was configured with another.
handshake_timeout (float) – As for
krpc.connect().stall_timeout (float) – As for
krpc.connect().
Raises
krpc.error.ConnectionErrorandValueErroraskrpc.connect()does.
- krpc.get_object_id(obj)#
The identifier of a remote object on the server, e.g. to pass to
KRPC.Expression.constant_object(). RaisesValueErrorif the object isNone.- Parameters:
obj – The remote object.
- Return type:
int
- class krpc.Connection#
A connection to the server, with an attribute for each of the server’s services. Obtain one by calling
krpc.connect(). It can be used in awithstatement, which closes it at the end of the block.- close()#
Closes the connection. Closing a connection that is already closed does nothing.
- krpc#
The
KRPCservice, providing the server’s basic functionality. The client uses some of its procedures itself, such as to add and remove streams, and your program does not need to call those. Each of the server’s other services is an attribute too, such asspace_center.
- add_stream(func, *args, **kwargs)#
Creates a stream for the remote procedure func called with arguments args and kwargs, and returns a
krpc.stream.Stream. Each call creates a new stream. Stream a property by passinggetattras func, then the object and the property’s name. Stream a property setter by passingsetattr, then the object, the property’s name and the value.func can also be a server side function, which the stream evaluates on each update. It is a
KRPC.Expressionobject, or a Python function or lambda that is compiled withcompile()on every call. A server side function takes no arguments.A call or function with no value runs on each update for its effects, and the stream’s value is
None.Raises
ValueErrorfor arguments passed with a server side function, and for a compiled function with parameters. RaisesTypeErrorfor any other value.
- stream(func, *args, **kwargs)#
Deprecated. Use
add_stream()in awithstatement.
- stream_update_condition#
A condition variable, of type
threading.Condition, notified after each stream update message is processed.
- wait_for_stream_update(timeout=None)#
Blocks until the next stream update message is processed, or the timeout elapses. The timeout is in seconds, and
Nonewaits indefinitely. Holdstream_update_conditionwhen calling this method.
- add_stream_update_callback(callback)#
Adds a callback, with no arguments, called after each stream update message is processed. It runs on the connection’s callback thread, as the callbacks of a stream do.
- remove_stream_update_callback(callback)#
Removes a stream update callback.
- run(function, *args, **kwargs)#
Runs a function on the server, within a single physics tick, and returns the value it produces. The value is
Nonewhen the function has no result or its result is null. The function is aKRPC.Expressionobject, or a Python function or lambda, which is compiled withcompile()on every call. The arguments are passed to the function’s parameters. A function built with the expression API takes positional arguments only.Raises
TypeErrorfor a value that is not a function, and for an argument its parameter cannot take, naming the argument’s position.
- add_event(function)#
Creates an event from a server side function that evaluates to a boolean value, and returns a
krpc.event.Event. The function can also be a Python function or lambda that takes no arguments, which is compiled withcompile()on every call.Raises
ValueErrorfor a compiled function with parameters, and for a function that does not evaluate to a boolean value. A value that is not a function raisesTypeError.
- compile(func)#
Compiles a Python function or lambda into a server side function, a
KRPC.Expressionobject. Adefcan take parameters, each with a type annotation. Can be used as a decorator. Raiseskrpc.error.CompilationErrorfor a construct with no server side equivalent. See Writing Server Side Functions. Given aKRPC.Expressionobject built with the expression API, compiles it on the server and returns it.
- get_call(func, *args, **kwargs)#
Converts a call to the remote procedure func with arguments args and kwargs into a
KRPC.ProcedureCallmessage, for use in a server side function built with the expression API. See The Expression API. Passgetattrorsetattras func for a property, as withadd_stream().
- get_call_template(func, *args)#
The call template of the remote procedure func, a
KRPC.ProcedureCallmessage that names the procedure and carries no arguments, forExpression.call_with_argumentsto supply each one. Takes the forms ofget_call(), with a class in place of the instance and no arguments, such asconn.get_call_template(getattr, Engine, "has_fuel")orconn.get_call_template(Engine.toggle_mode), whereEngineisconn.space_center.Engine. A member passed where a call is expected, such asEngine.has_fuelorEngine.toggle_mode, is converted to its call template, and a property gives its getter’s. Raises aTypeErrorfor a member reached through an object. Functions and Collections uses a call template.
- class krpc.stream.Stream#
A stream. See Streaming Data.
- __call__()#
Returns the most recent value of the stream, waiting for the first value if none has arrived yet. Raises the exception that ended the stream, if it has ended.
- wait(timeout=None)#
Blocks until the value of the stream changes, or the timeout elapses. Returns
Trueif the value changed, andFalseon a timeout. Holdconditionwhen calling this method.The timeout is in seconds, and
Nonewaits indefinitely. RaisesValueErrorfor a negative timeout. Raises the exception that ended the stream, if it ends before or during the wait. A thread holding the condition sees an ending as an update: the wait returnsTrue, and later reads and waits raise the exception.
- condition#
A condition variable, of type
threading.Condition, notified when the value of the stream changes.
- rate#
The update rate of the stream, in Hertz. Zero, the default, means no limit.
- add_callback(callback)#
Adds a callback, called with each new value of the stream. If the stream already has a value, the callback is called with it straight away. The exception that ends a stream goes to its end callbacks.
- remove_callback(callback)#
Removes a callback.
- add_end_callback(callback)#
Adds a callback, called once when the stream ends, with the exception that ended it. It is called straight away if the stream has already ended.
- remove_end_callback(callback)#
Removes an end callback.
- remove()#
Removes the stream from the server. Other streams of the same call are not affected. Leaving a
withstatement on the stream does the same.
- class krpc.event.Event#
An event, made from a stream of
boolthat is true when the event fires. See Events.- wait(timeout=None)#
Blocks until the event fires, or the timeout elapses. Returns straight away if the event has fired since the previous wait. Returns
Trueif the event fired, andFalseon a timeout. Holdconditionwhen calling this method.The timeout is in seconds, and
Nonewaits indefinitely. RaisesValueErrorfor a negative timeout. Raises the exception that ended the event, if it ends before or during the wait.
- condition#
A condition variable, of type
threading.Condition, notified when the event fires.
- add_callback(callback)#
Adds a callback, with no arguments, called each time the event fires. It is called straight away for a firing that no wait has returned for and no callback has been called for.
- remove_callback(callback)#
Removes a callback.
- add_end_callback(callback)#
Adds a callback, called once when the event ends, with the exception that ended it. It is called straight away if the event has already ended.
- remove_end_callback(callback)#
Removes an end callback.
- remove()#
Removes the event from the server. Leaving a
withstatement on the event does the same.
- stream#
The stream the event is made from.
- class krpc.error.RemoteError#
The base of every error the client raises of its own. A subclass of
RuntimeError.
- class krpc.error.ConnectionError#
Raised when connecting fails, and by each call once the connection has closed or failed. A subclass of
krpc.error.RemoteError. It shadows the builtinConnectionError, andexcept OSErrordoes not catch it.- status#
The status the server refused the connection with, such as
"DENIED", orNone.
- reason#
The reason the server gave for ending the connection, such as
"SERVER_STOPPED", orNone.
- class krpc.error.ServerError#
Raised for an error from the server with no builtin type, and the base of the exception classes the services declare. A subclass of
krpc.error.RemoteError.
- class krpc.error.StreamError#
Raised by a stream or event that you or the server removed, and when a stream cannot be created. A subclass of
krpc.error.RemoteError.
- class krpc.error.EncodingError#
Raised for a value of the right type that cannot be encoded, and for a value that cannot be decoded. A subclass of
krpc.error.RemoteError.
- class krpc.error.CompilationError#
Raised when a Python function cannot be compiled into a server side function. The error message names the unsupported construct. See Writing Server Side Functions. A subclass of
krpc.error.RemoteError.
Numeric Limits#
The krpc.limits module names the extremes of the numeric types kRPC carries over the wire.
Python integers are unbounded, and Python floats are C doubles, so the standard library covers
DOUBLE alone. A service can declare one of these limits as a parameter’s default value, and
the generated module then names the constant from this module.
The minimum of an unsigned type is 0, so it has no constant.
- krpc.limits.DOUBLE_MAX#
- krpc.limits.DOUBLE_LOWEST#
The largest and most negative finite 64-bit float.
- krpc.limits.SINT32_MAX#
- krpc.limits.SINT32_MIN#
The largest and most negative 32-bit signed integer.
- krpc.limits.SINT64_MAX#
- krpc.limits.SINT64_MIN#
The largest and most negative 64-bit signed integer.
- krpc.limits.UINT32_MAX#
The largest 32-bit unsigned integer.
- krpc.limits.UINT64_MAX#
The largest 64-bit unsigned integer.
Service API Reference#
Server