Modify Python code as newbie
MRAB
python at mrabarnett.plus.com
Fri Jan 17 20:31:25 EST 2020
On 2020-01-18 00:34, ron.eggler at ecoation.com wrote:
> Hi,
>
> I'm semi new to Python but need to modify a program that calls the mqtt_client.publish() function from aws iot.
> Now, if the publish function fails, it raises an exception. I need to change the code so that when an exception is raised, instead of giving up, it should retry.
> Here's some semi pseudo code of what I came up with and what I'm particularly interested in is, if the exception in pub_msg() is raised, will my thread t keep running?
> What else could/should be improved about the below snippet? I'm looking forward to get some inputs.
>
> Thanks!
>
>
> import retrying
> import Queue as queue
Is this Python 2? In Python 3 it's called "queue".
> import threading as th
> NUM_THREADS=1
> numth=[]
> def worker():
> while not_terminated():
> item = q.get()
> if item is None:
> continue
> do_stuff(item)
>
> def enQ(self, msg, topic):
> if len(numth<int(NUM_THREADS):
Missing ")".
> t = th.Thread(target=worker)
> t.start()
> numth.append(t)
> q.put([self,msg,topic])
>
> def do_stuff(dat):
> self = dat[0]
> msg = dat[1]
> topic = dat[2]
> pub-msg(slef, msg, topic)
The "-" should be "_" and "slef" should be "self".
>
> def send_msg(self, msg,topic):
> enQ(self,msg,topic)
>
> def pub_msg(self,msg,topic):
> try:
> if topic == "test" and \
> something[self.xyz]:
> return
> except KeyError as err:
> foo("Exception {}".format(err))
"except" block is indented too much.
If there's a key error, it'll call "foo" (whatever that is) and then
continue.
>
> aws_publish(self,msg,topic)
>
> @retry (wait_random_min=1000, wait_random_max=2000)
> def aws_publish(self.msg,topic):
"." instead of ",".
> self.__mqtt_client.publish(
> "/{}/{}".format(topic, self._uuid), msg_json, 1)
>
More information about the Python-list
mailing list