Debian Codegraph @

python/examples/selected_recv.py

raw
1 #!/usr/bin/env python3
2 #
3 # Licensed to the Apache Software Foundation (ASF) under one
4 # or more contributor license agreements. See the NOTICE file
5 # distributed with this work for additional information
6 # regarding copyright ownership. The ASF licenses this file
7 # to you under the Apache License, Version 2.0 (the
8 # "License"); you may not use this file except in compliance
9 # with the License. You may obtain a copy of the License at
10 #
11 # http://www.apache.org/licenses/LICENSE-2.0
12 #
13 # Unless required by applicable law or agreed to in writing,
14 # software distributed under the License is distributed on an
15 # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16 # KIND, either express or implied. See the License for the
17 # specific language governing permissions and limitations
18 # under the License.
19 #
20
21 import optparse
22 from proton import Url
23 from proton.reactor import Container, Selector
24 from proton.handlers import MessagingHandler
25
26
27 class Recv(MessagingHandler):
28 def __init__(self, url, count):
29 super(Recv, self).__init__()
30 self.url = Url(url)
31 self.expected = count
32 self.received = 0
33
34 def on_start(self, event):
35 conn = event.container.connect(self.url)
36 event.container.create_receiver(conn, self.url.path, options=Selector("colour = 'green'"))
37
38 def on_message(self, event):
39 print(event.message.body)
40 self.received += 1
41 if self.received == self.expected:
42 event.receiver.close()
43 event.connection.close()
44
45
46 parser = optparse.OptionParser(usage="usage: %prog [options]")
47 parser.add_option("-a", "--address", default="localhost:5672/examples",
48 help="address from which messages are received (default %default)")
49 parser.add_option("-m", "--messages", type="int", default=0,
50 help="number of messages to receive; 0 receives indefinitely (default %default)")
51 opts, args = parser.parse_args()
52
53 try:
54 Container(Recv(opts.address, opts.messages)).run()
55 except KeyboardInterrupt:
56 pass