Skip to content

Instantly share code, notes, and snippets.

@dtheodor
Created December 18, 2014 21:30
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save dtheodor/126fc329960a714f1945 to your computer and use it in GitHub Desktop.
Save dtheodor/126fc329960a714f1945 to your computer and use it in GitHub Desktop.
Listen for pg_notify with Psycopg2
import select
import datetime
import psycopg2
import psycopg2.extensions
conn = psycopg2.connect(database="postgres", user="vagrant")
#conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
curs = conn.cursor()
curs.execute("LISTEN test;")
curs.execute("LISTEN lol;")
seconds_passed = 0
print "Waiting for notifications on channel 'test'"
while 1:
conn.commit()
if select.select([conn],[],[],5) == ([],[],[]):
seconds_passed += 5
print "{} seconds passed without a notification...".format(seconds_passed)
else:
seconds_passed = 0
conn.poll()
conn.commit()
while conn.notifies:
notify = conn.notifies.pop()
print "Got NOTIFY:", datetime.datetime.now(), notify.pid, notify.channel, notify.payload
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment