Home > Net >  How to run commands synchronously in Python
How to run commands synchronously in Python

Time:10-03

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

CodePudding user response:

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

CodePudding user response:

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.

  • Related