[파이썬] subprocess `subprocess.DETACHED_PROCESS`: 분리된 프로세스 시작

In Python, the subprocess module allows you to create and manage subprocesses. One of the options available is subprocess.DETACHED_PROCESS, which starts a subprocess in a detached mode.

When a subprocess is started in detached mode, it is independent of the parent process. It continues executing even if the parent process terminates. This can be useful in situations where you want a process to run in the background or as a daemon.

Here’s an example of how to use subprocess.DETACHED_PROCESS to start a detached subprocess:

import subprocess

# Command to execute in the subprocess
command = ['python', 'script.py']

# Start the subprocess in detached mode
subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, creationflags=subprocess.DETACHED_PROCESS)

In the example above, we’re using the Popen function from the subprocess module to start a new process. The command variable contains the command to be executed in the subprocess. In this case, we’re running the script.py script using the python interpreter.

To run the subprocess in detached mode, we pass the creationflags=subprocess.DETACHED_PROCESS argument. This tells the Popen function to start the subprocess in a detached state.

Additionally, we’re redirecting the standard input, output, and error streams of the subprocess to subprocess.DEVNULL. This prevents them from being tied to the parent process and allows the subprocess to run independently.

Keep in mind that when running a subprocess in detached mode, you won’t have direct control or visibility over its execution. If you need to interact with the subprocess or monitor its output, you may consider using other options from the subprocess module, such as subprocess.PIPE.

Overall, using subprocess.DETACHED_PROCESS can be a powerful tool to start independent subprocesses in Python. It gives you the flexibility of running processes in the background or as daemons, allowing you to perform various tasks simultaneously.