Sobes.tech
Middle

What is the wait() function and how is it used in Python?

sobes.tech AI

Answer from AI

The wait() method in Python's multiprocessing is used to suspend the current parent process until the child process on which wait() is called finishes.

Main features and usage:

  • Synchronization: Ensures that the parent process does not continue until the child process finishes.
  • Get exit status: Returns the exit code of the child process. Code 0 usually means success, non-zero indicates an error.
  • Blocking behavior: wait() is blocking. The current process will wait indefinitely unless a timeout is specified.
  • Timeout: Can accept an optional timeout argument, specifying the maximum wait time in seconds. If the child does not finish in that time, a TimeoutExpired exception is raised.
import multiprocessing
import time
def worker():
    # Simulate long task
    time.sleep(3)
    print("Child process finished")
    return 0

if __name__ == "__main__":
    process = multiprocessing.Process(target=worker)
    process.start()
    print("Waiting for child process...")
    exit_code = process.wait()  # Wait and get exit code
    print(f"Child process exited with code: {exit_code}")
    # Example with timeout
    process_with_timeout = multiprocessing.Process(target=worker)
    process_with_timeout.start()
    try:
        exit_code_timeout = process_with_timeout.wait(timeout=1)  # Max wait 1 sec
        print(f"Child process with timeout exited with code: {exit_code_timeout}")
    except multiprocessing.TimeoutError:
        print("Child process with timeout did not finish in time")
        process_with_timeout.terminate()  # Terminate process if timeout
import subprocess

# Example of wait() in subprocess
process = subprocess.Popen(["ls", "-l"])
return_code = process.wait()  # Wait for process to finish
print(f"Process finished with code: {return_code}")

Comparison with join():

Method Module Main purpose Return value Timeout
wait() multiprocessing, subprocess Wait for child process to finish Exit code of child process Available
join() multiprocessing, threading Wait for thread or process to finish None Available

In multiprocessing, wait() and join() may seem similar. But wait() is used to get the exit code, while join() just waits for completion without returning status. In subprocess, wait() is the main method to wait for an external process to finish and get its return code.