Skip to content

Commit 0076462

Browse files
Merge pull request #275 from karl-johan-grahn/python-tutorial-1-keyboardinterrupt
Python Tutorial 1 - Handle KeyboardInterupt
2 parents 5097932 + 72852d4 commit 0076462

File tree

1 file changed

+19
-12
lines changed

1 file changed

+19
-12
lines changed

python/receive.py

Lines changed: 19 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,26 @@
11
#!/usr/bin/env python
2-
import pika
2+
import pika, sys, os
33

4-
connection = pika.BlockingConnection(
5-
pika.ConnectionParameters(host='localhost'))
6-
channel = connection.channel()
4+
def main():
5+
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
6+
channel = connection.channel()
77

8-
channel.queue_declare(queue='hello')
8+
channel.queue_declare(queue='hello')
99

10+
def callback(ch, method, properties, body):
11+
print(" [x] Received %r" % body)
1012

11-
def callback(ch, method, properties, body):
12-
print(" [x] Received %r" % body)
13+
channel.basic_consume(queue='hello', on_message_callback=callback, auto_ack=True)
1314

15+
print(' [*] Waiting for messages. To exit press CTRL+C')
16+
channel.start_consuming()
1417

15-
channel.basic_consume(
16-
queue='hello', on_message_callback=callback, auto_ack=True)
17-
18-
print(' [*] Waiting for messages. To exit press CTRL+C')
19-
channel.start_consuming()
18+
if __name__ == '__main__':
19+
try:
20+
main()
21+
except KeyboardInterrupt:
22+
print('Interrupted')
23+
try:
24+
sys.exit(0)
25+
except SystemExit:
26+
os._exit(0)

0 commit comments

Comments
 (0)