How to spin up a docker container/vm on demand in python?

I am building a system where I basically accept untrusted python programs from users and run it.

My approach is to spin up a docker container (or any VM) on demand for each python script and run it in there. I will want to set custom cpu/memory parameters for each container.

What’s the easiest way to accomplish this?

Source: StackOverflow