30

In python, is there a way to invoke a new process in, hand it the same context, such as standard IO streams, close the current process, and give control to the invoked process? This would effectively 'replace' the process.

I have a program whose behavior I want to repeat. However, it uses a third-party library, and it seems that the only way that I can truly kill threads invoked by that library is to exit() my python process.

Plus, it seems like it could help manage memory.

eacousineau
  • 3,457
  • 3
  • 34
  • 37

1 Answers1

38

You may be interested in os.execv() and friends:

These functions all execute a new program, replacing the current process; they do not return. On Unix, the new executable is loaded into the current process, and will have the same process id as the caller. Errors will be reported as OSError exceptions.

detly
  • 29,332
  • 18
  • 93
  • 152
  • 10
    Note that a call would look somewhat like `os.execvp('python.exe', ['python.exe', 'arg1', 'arg2'])`. Note the somewhat counter-intuitive `'python.exe'` appearing twice. See [this answer](http://stackoverflow.com/a/18552137/1143274) for more details. – Evgeni Sergeev Oct 22 '14 at 12:55
  • Is there an equivalent `subprocess` call we're supposed to use? – tback Jul 11 '22 at 07:18
  • 1
    @tback - Not really - it's much more of a platform-specific thing, and generally considered a lot more niche than spawning a *separate* subprocess. – detly Jul 11 '22 at 09:00