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")

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.

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

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.