dev/osc/ TrivialExamplesInPython


Send and Receive

Install pythonosc via python -m pip install pythonosc

Sender (host,port hardwired to pair with receiver script below)

from pythonosc import udp_client
client = udp_client.SimpleUDPClient("localhost",7001)
def s(path,*args):
  print(f"Sending {path=} {args=}")
  client.send_message(path,args)

# either add code to send messages here, or run with python -i (interactive)
# so that you can e.g.
s("/hello","world")

Receiver (note that host and port are hardwired to save writing code to handle env vars and command line params).

from pythonosc import dispatcher,osc_server
def fmt(x):
  'turn numbers into strings, and add "quotes" to strings'
  if type(x) in (int,float):
    return str(x)
  elif type(x) is str:
    if '"' in x and not "'" in x:
      return f"'{x}'"
    else:
      x = x.replace('"',r'\"')
      return f'"{x}"'
def dump(*xs):
  n,*ys = xs
  print(f"{n}: {', '.join(map(fmt,ys))}")

disp = dispatcher.Dispatcher()
disp.set_default_handler(dump)
serv = osc_server.ThreadingOSCUDPServer(("localhost",7001),disp)
print(f"Serving")
serv.serve_forever()