I have a sequence of messages in json and they include a field called part, which is an integer from 0 to 2. I have three message queues and the value of part determines which queue I send the message over to.
This is my current code.
output0 = queue.Queue()
output1 = queue.Queue()
output2 = queue.Queue()
json = json.loads('{"test": "message", "part": "2"}')
part = int(json["part"])
if part == 0:
output0.put(json)
elif part == 1:
output1.put(json)
elif part == 2:
output2.put(json)
I'd like to simplify it with something like.
chooseQueue = "output" + str(json["part"])
chooseQueue.put(json)
It serves me this error AttributeError: 'str' object has no attribute 'put'
In R, I can use a string as a variable name by using as.formula() or get().
The answer to your question is locals().
The answer to you problem is a dict
queue_dict = {'1': queue.Queue(), '2': queue.Queue(), '3': queue.Queue()}
queue = queue_dict[json["part"]]
You can, but you'd be much better off keeping your queues in a dict:
queues = {"output0": queue.Queue(),
"output1": queue.Queue(),
"output2": queue.Queue(),
}
chooseQueue = "output" + str(json["part"])
queues[chooseQueue].put(json)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With