Skip to content Skip to sidebar Skip to footer

Running Subsequent Commands Within Python

I would like to be able to call two (or more) commands within python but I would like to make sure that the first is finished before the second starts. Is that possible with subpro

Solution 1:

A call to subprocess.call blocks until the command completes. From the documentation:

Wait for command to complete, then return the returncode attribute.

A similar option that also waits for completion is subprocess.check_call. The difference between call and check_call is that the latter raises an exception for a nonzero return code, whereas the former returns the return code for all cases.

Solution 2:

From the documentation:

Run the command described by args. Wait for command to complete, then return the returncode attribute.

To do it asynchronously (so that you aren't waiting) you would use subprocess.Popen.

Solution 3:

Are you trying to reproduce a shell pipeline?

If so, then, adapting the example from the python docs, your example might become:

from subprocess import Popen, PIPE
p1 = Popen([script1, input1], stdout=PIPE)
p2 = Popen([script2], stdin=p1.stdout, stdout=PIPE)
p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits.
output = p2.communicate()[0]

Post a Comment for "Running Subsequent Commands Within Python"