What is the correct way to close a subprocess object when we finish using it?
stdout.close() and stdin.close() do not terminate the process if it does not exit the end of the input or write errors.
.terminate() and .kill() both do the job, with kill will be a bit more "radical" on POSIX systems, since SIGKILL sent, which cannot be ignored by the application. Specific differences are explained, for example, in this blog post . There is no difference in Windows.
Also, don't forget .wait() and close the pipes after killing the process to avoid the zombies and force them to free up resources.
A common case that often occurs are processes that are read from STDIN and write their result to STDOUT, closing when an EOF is encountered. With such programs, it is often wise to use subprocess.communicate :
>>> p = Popen(["sort"], stdin=PIPE, stdout=PIPE) >>> p.communicate("4\n3\n1") ('1\n3\n4\n', None) >>> p.returncode 0
This can also be used for programs that print something and exit immediately after:
>>> p = Popen(["ls", "/home/niklas/test"], stdin=PIPE, stdout=PIPE) >>> p.communicate() ('file1\nfile2\n', None) >>> p.returncode 0
Given the nature of my script, is there a way to open a subprocess object only once and reuse it with different shell commands? Would it be more efficient than opening new subprocess objects every time?
I donβt think the subprocess module supports this, and I donβt see what resources can be shared here, so I donβt think it will give you a significant advantage.