This section contains snippets demonstrating OpenTelemetry context propagation in Python, both within the same process (intra-process) and across different processes (inter-process).
Configuring environment
Development Environment
You can run otel-tui as OpenTelemetry Collector, which acts as a terminal OpenTelemetry viewer
importtimeimportthreadingfromtypingimportAnyimportrequestsfromflaskimportFlask,jsonify,requestfromopentelemetryimporttrace,propagatefromopentelemetry.sdk.traceimportTracerProviderfromopentelemetry.sdk.resourcesimportResourcefromopentelemetry.sdk.trace.exportimportBatchSpanProcessorfromopentelemetry.exporter.otlp.proto.grpc.trace_exporterimport(OTLPSpanExporter,)resource=Resource.create({"service.name":"context-propagation-interprocess"})provider=TracerProvider(resource=resource)trace.set_tracer_provider(provider)provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter(endpoint="http://localhost:4317",insecure=True)))tracer=trace.get_tracer(__name__)app=Flask(__name__)@app.route("/api/data",methods=["GET"])defget_data():# Extract context from incoming request headersctx=propagate.extract(request.headers)# Start span with extracted context as parentwithtracer.start_as_current_span("server_operation",context=ctx)asspan:span.set_attribute("server.endpoint","/api/data")span.add_event("Processing request on server")result={"message":"Hello from server","data":[1,2,3]}span.add_event("Request processed successfully")returnjsonify(result)defstart_server():app.run(host="localhost",port=5001,debug=False,use_reloader=False)defmake_http_request()->dict[str,Any]:withtracer.start_as_current_span("client_operation")asspan:span.set_attribute("client.operation","fetch_data")span.add_event("Making HTTP request")headers={"Content-Type":"application/json"}# Inject current span context into headerspropagate.inject(headers)try:# Make HTTP request with propagated contextresponse=requests.get("http://localhost:5001/api/data",headers=headers)span.set_attribute("http.status_code",response.status_code)span.add_event("HTTP request completed")returnresponse.json()exceptExceptionase:span.add_event("HTTP request failed",{"error":str(e)})return{"error":str(e)}server_thread=threading.Thread(target=start_server,daemon=True)server_thread.start()time.sleep(2)# Wait for server to startmake_http_request()
Run this Python snippet
uv run https://emdneto.github.io/opentelemetry-by-example/python/context-propagation/snippet_interprocess.py