I am trying to create a child process with Python under a new Linux namespace. But checking the subprocess documentation it does not seem as though Python actually has an API to do so. The closest thing I found is the unshare
method in the os
module (here). But that seems to require these steps:
That's not quite the same as creating an isolated process to start with. Is there indeed no simple API in Python for this?
As an example, here is the analogous code in Go:
cmd := exec.Command(...)
cmd.SysProcAttr = &syscall.SysProcAttr {
Cloneflags: syscall.CLONE_NEWUTS
}
cmd.Run()
The question is how to achieve the same with Python.
There is no other nice Python API for this. os.unshare()
and os.setns()
are currently the only APIs for manipulating namespaces (since Python 3.12). The feature request also mentions this:
As for now, changing to a different namespace is really messy, one must use ctypes, and call libc functions to do so. I think implementing setns and unshare functions will make working with namespaces in Python much easier
You could of course manually issue a clone
syscall with CLONE_NEWxxx
flags either through ctypes
(loading the C library), but that would be pretty messy and definitely unsafe as it wouldn't take into account things like internal interpreter locks etc.