It seems I may just have been a bit dumb. This is just not a very good way to do this with python a much better approach came from this post. which led me to these docs.
The previously marked correct answer is still correct, this is just a bit of bonus info.