[파이썬] subprocess `subprocess.Popen` 객체의 `stdout` 속성

When working with subprocesses in Python, the subprocess.Popen class is commonly used to spawn new processes and interact with them. One of the most important attributes of the Popen object is stdout, which represents the standard output of the subprocess.

What is stdout?

stdout is an abbreviation for standard output. In the context of the Popen object, stdout refers to the output pipe connected to the standard output stream of the subprocess. It provides a way to capture and read the output generated by the subprocess.

Accessing the stdout attribute

To access the stdout attribute of a subprocess.Popen object, you can simply use the dot notation. Here’s an example:

import subprocess

# Execute a command and capture the stdout
process = subprocess.Popen(['echo', 'Hello, World!'], stdout=subprocess.PIPE)
stdout = process.stdout

# Read the output
output = stdout.read()

# Print the output
print(output.decode())

In the above code, we create a Popen object using the subprocess.Popen function. We pass the command we want to execute (echo 'Hello, World!') as a list of arguments. By setting the stdout=subprocess.PIPE parameter, we tell the subprocess to redirect its standard output to a pipe, which allows us to capture it.

We then access the stdout attribute of the Popen object using process.stdout. This provides us with a file-like object that represents the output stream of the subprocess. We can read the output by calling the read method on this object.

Finally, we decode the output using the decode method with the appropriate encoding and print it to the console.

Using stdout in real-world scenarios

The stdout attribute is particularly useful when you need to capture the output of a subprocess and use it in your code. This allows you to process the output, analyze it, or use it as input for other operations or subsequent subprocesses.

For example, you could use stdout to capture the output of a command-line utility and parse it to extract specific information or use it to make decisions within your Python program.

Conclusion

The stdout attribute of the subprocess.Popen object provides a way to capture and read the standard output of a subprocess. By leveraging this attribute, you can easily interact with the output of external commands and integrate it into your Python programs.