[파이썬] subprocess `subprocess.terminate()`: 프로세스 종료

In Python, the subprocess module provides a way to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. When working with processes, there may be situations where you need to forcefully terminate a running process. This is where the subprocess.terminate() method comes into play.

Understanding subprocess.terminate()

The subprocess.terminate() method is used to terminate a running process initiated using the subprocess module. It sends a termination signal to the process, requesting it to gracefully exit. This signal is the same as the SIGTERM signal in Unix-like systems, which is the default termination signal.

Example Usage

Let’s consider an example where we start a long-running process using subprocess.Popen() and then terminate it using subprocess.terminate():

import subprocess
import time

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

# Allow the process to run for some time
time.sleep(5)

# Terminate the process
process.terminate()

In the above code snippet, we import the subprocess module and also time module for demonstration purposes. We start a long-running process (here, a Python script called my_script.py) using subprocess.Popen(). Then, we allow the process to run for 5 seconds using time.sleep(5). Finally, we terminate the process using process.terminate().

Handling Terminated Process

After calling subprocess.terminate(), the terminated process will exit and return control to your Python script. However, it is important to note that this does not guarantee immediate process termination. The process may require some time to clean up resources and shut down gracefully.

To handle the termination of the process more specifically, you can use the subprocess.poll() method. This method returns None if the process is still running or returns the process’s exit code if it has terminated.

# Poll the process if it has terminated or not
return_code = process.poll()
if return_code is not None:
    print(f"Process terminated with exit code {return_code}")
else:
    print("Process still running...")

In the code snippet above, after calling process.terminate(), we use process.poll() to check if the process has terminated or not. If the return code is not None, it means that the process has terminated and we can print the exit code. Otherwise, we indicate that the process is still running.

Conclusion

The subprocess.terminate() method in Python provides a simple way to terminate a running process spawned using the subprocess module. In this blog post, we learned how to use subprocess.terminate() to terminate a process and also how to check if the process has terminated using subprocess.poll(). Remember to use this method judiciously, considering the impact it may have on the state of the process and the resources it is using.