[파이썬] subprocess `subprocess.start_new_session`: 새 세션에서 시작

In Python, the subprocess module provides a wide range of functionality for spawning and interacting with new processes. One of the useful functions available in this module is subprocess.start_new_session, which allows you to start a new process in its own session.

What is a Session?

A session, in the context of operating systems, is a way to group related processes together. Each session has a leader process, which is the first process in the session that created it. When a session leader terminates, all processes in the session are terminated as well.

The subprocess.start_new_session Function

The subprocess.start_new_session function allows you to start a new process in its own session. This function takes the same arguments as the subprocess.Popen function, which is used to create a new process. The difference is that the start_new_session function sets the preexec_fn argument to os.setsid, which creates a new session for the child process.

Here is an example of how to use subprocess.start_new_session:

import subprocess

command = ['python', 'script.py']

# Start a new process in a new session
process = subprocess.start_new_session(cmd=command)

# Continue with the parent process
print("Parent process continues...")

In the example above, we are starting a new process by passing the cmd argument to subprocess.start_new_session. The cmd argument is a list of command-line arguments for the new process. In this case, we are starting a Python script called script.py.

After starting the new process, the parent process continues executing the next line of code. This is useful if you want to perform other tasks while the child process is running in its own session.

Benefits of Using a New Session

There are several benefits to starting a new process in its own session:

Conclusion

The subprocess.start_new_session function in Python’s subprocess module provides a convenient way to start a new process in its own session. By creating a new session, you can take advantage of the benefits it offers, such as process isolation and independence from the parent process. This can be useful in a variety of scenarios, such as running background tasks or executing processes with different settings.