1

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 subprocess? For example:

subprocess.call("script1 input1 > out", shell=True)

and when that command finishes:

subprocess.call("script2 out>out2", shell=True)

or is there a better way?

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@BrianCain Thank you for the suggestion. I have updated to answer to include information about subprocess.check_call.
1

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.

Comments

0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.