[파이썬] subprocess `Popen.poll()`: 프로세스 상태 체크

In Python, the subprocess module provides a way to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. One useful method provided by the subprocess module is Popen.poll(), which allows us to check the status of a process.

What is Popen.poll()?

Popen.poll() is a method of the Popen class in the subprocess module. It is used to check the status of a child process without blocking. This means that it will not wait for the process to finish before returning the result. Instead, it will immediately return the process’s return code if it has completed, or None if it is still running.

How to use Popen.poll()?

To use Popen.poll(), you first need to create a Popen object by calling the subprocess.Popen() function. This function takes a list or string of command-line arguments and various other optional parameters. Once you have the Popen object, you can call Popen.poll() to check its status.

Here’s an example that demonstrates the usage of Popen.poll():

import subprocess

# Start a process
process = subprocess.Popen(["python", "my_script.py"])

# Check the status of the process
return_code = process.poll()

if return_code is None:
    print("Process is still running.")
else:
    print(f"Process has completed with return code: {return_code}")

In the above example, we use subprocess.Popen() to start a new process running the my_script.py Python script. We then call process.poll() to check the status of the process. If the return code is None, it means the process is still running. Otherwise, it has completed, and we print the return code.

Conclusion

The subprocess module in Python provides a convenient way to spawn and control new processes. The Popen.poll() method allows us to check the status of a process without blocking. This can be useful when you need to monitor the progress of a long-running external command or handle situations where multiple processes need to be managed concurrently.