from google.cloud import pubsub
subscriber = pubsub.SubscriberClient()
# Define the callback.
# Note that the callback is defined *before* the subscription is opened.
def callback(message):
do_something_with(message) # Replace this with your actual logic.
message.ack()
# Open the subscription, passing the callback.
future = subscriber.subscribe(
'projects/{project}/subscriptions/{subscription}',
callback
)
# To block the thread you are in while messages are
# coming in the stream, use the result() method
try:
future.result()
except Exception as ex:
subscription.close()
raise
# Finally, you can use cancel() to stop receiving messages.
future.cancel()