Skip to content

Instantly share code, notes, and snippets.

@SebastianBitsch
Last active March 20, 2025 11:36
Show Gist options
  • Save SebastianBitsch/1d3074feb2bcff384f6242ef35cd8246 to your computer and use it in GitHub Desktop.
Save SebastianBitsch/1d3074feb2bcff384f6242ef35cd8246 to your computer and use it in GitHub Desktop.
Minimal python scripting language

Minimal Python scripting language

The example contains just a simple command interpreter for setting, getting, and persisting variables. It is meant as a demo that could be extended with more commands and more complex functionality to use in for instance ROS2.

Uses a command lookup system (COMMANDS dictionary) to map user input to the appropriate functions and execute them. The user interacts with the program through a basic REPL (Read-Eval-Print Loop) in the command_loop().

Commands:

  • help : Print information about commands
  • set <var_name> <value>: Set a variable with a given name to a specific value.
  • get <var_name>: Retrieve and print the value of a variable.
  • save <path>: Save the current state of variables to a JSON file.
  • load <path>: Load the variables' state from a previously saved JSON file.

Example Usage:

>> set x 10
>> get x
10
>> save example.json
>> set x 100
>> get x
100
>> load example.json
>> get x
10
# Minimal python scripting language which can be used as a starting off point
import json
VARIABLES = {}
def set_var(name: str, val) -> None:
""" Set the value of a variable, e.g. `set pi 3.14`"""
VARIABLES[name] = val
def get_var(name: str):
""" Print the value of a stored variable """
if name in VARIABLES:
print(VARIABLES[name])
def save(name: str) -> None:
""" Save the current configuration to a json file with a given name """
json.dump(VARIABLES, open(name, 'w'))
def load(name: str) -> None:
""" Load a configuration json by name """
global VARIABLES
VARIABLES = json.load(open(name))
def print_help() -> None:
""" Print this help window """
for name, fn in COMMANDS.items():
print(f"- {name:<10}:{fn.__doc__}")
COMMANDS = {
"help" : print_help,
"set" : set_var,
"get" : get_var,
"save" : save,
"load" : load,
}
def command_loop():
while True:
try:
user_input = input(">> ")
parts = user_input.split()
if len(parts) == 0:
continue
command_name = parts[0]
args = parts[1:]
COMMANDS[command_name](*args)
except Exception as e:
print(f"Error: {e}")
if __name__ == "__main__":
command_loop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment