0

I'm am making a DVD ripping script and need to run commands synchronously for my script to work properly. I have been trying to using subprocess with no success. This test code should run for at least 7 seconds.

import subprocess
import time
start_time = time.time()
p1 = subprocess.Popen(['timeout', "2"], shell=False,
 stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
p2 = subprocess.Popen(['timeout', "5"], shell=False,
 stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
print(f"Finshed in {time.time() - start_time} Seconds")
juanpa.arrivillaga
97.7k14 gold badges141 silver badges190 bronze badges
asked Oct 2, 2021 at 18:52

2 Answers 2

2

You can use the Popen.wait method, which waits for the subprocess to terminate:

import subprocess
import time
start_time = time.time()
p1 = subprocess.Popen(['sleep', "2"], shell=False,
 stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
p1.wait()
p2 = subprocess.Popen(['sleep', "5"], shell=False,
 stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
p2.wait()
print(f"Finshed in {time.time() - start_time} Seconds")

If I run this:

(py39) Juans-MacBook-Pro:~ juan$ python -B stackoverflow.py
Finshed in 7.015462160110474 Seconds

Note, the subprocess docs recommend you use the subprocess.run helper function, which happens to automatically block until the subprocess terminates. It returns a subprocess.CompletedProcess object. So:

import subprocess
import time
start_time = time.time()
result1 = subprocess.Popen(['sleep', "2"], shell=False,
 stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
result2 = subprocess.run(['sleep', "5"], shell=False,
 stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
print(f"Finshed in {time.time() - start_time} Seconds")

would be another approach.

answered Oct 2, 2021 at 19:06
Sign up to request clarification or add additional context in comments.

1 Comment

I used it on HandbrakeCLI and it worked great! Thanks for the fast reply.
1

Use .run() [1]

import subprocess
import time
start_time = time.time()
p1 = subprocess.run(['sleep', "2"])
p2 = subprocess.run(['sleep', "5"])
print(f"Finshed in {time.time() - start_time} Seconds")

[1] https://docs.python.org/3/library/subprocess.html#subprocess.run

answered Oct 2, 2021 at 19:13

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.