[파이썬] subprocess `subprocess.STDOUT`: 표준 출력 연결

subprocess.STDOUT is a special constant in the subprocess module that is used to indicate that the standard output of a subprocess should be redirected to the standard output of the current process. In other words, it allows us to capture the output of a subprocess and display it directly in our terminal or console.

To use subprocess.STDOUT, you will need to import the subprocess module in your Python script. Here’s an example code snippet that demonstrates how to leverage subprocess.STDOUT:

import subprocess

# Run a shell command and capture the output
command = "ls -l"  # Example shell command
result = subprocess.run(command.split(), stdout=subprocess.STDOUT, text=True, check=True)

# Print the output of the subprocess
print(result.stdout)

In this example, we use the subprocess.run() function to execute a shell command (ls -l in this case) and capture its output. By passing stdout=subprocess.STDOUT as a parameter, we redirect the subprocess’s standard output to the current process’s standard output. The captured output is then stored in the result.stdout attribute.

By printing result.stdout, we can display the output of the subprocess directly in the terminal or console where the Python script is executed.

Using subprocess.STDOUT gives you flexibility and control over handling the output of a subprocess. You can combine it with other features of the subprocess module, such as capturing the standard error, passing arguments to the command, or specifying the working directory.

So, the next time you need to capture and display the output of a subprocess in Python, remember to make use of subprocess.STDOUT for a seamless experience.