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:
- Create a child process in the same namespace as the current parent
- Run unshare isolate the child process
- Run the command(s) we wanted in the child process
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()andos.setns()are currently the only APIs for manipulating namespaces (since Python 3.12). The feature request also mentions this:You could of course manually issue a
clonesyscall withCLONE_NEWxxxflags either throughctypes(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.