[파이썬] subprocess `subprocess.capture_output`: 출력 캡처 설정

In Python, the subprocess module provides a way to execute external commands or interact with the system shell. One common task when working with subprocesses is capturing the output from the executed command, which can be done using the subprocess.capture_output function.

What is subprocess.capture_output?

subprocess.capture_output is a convenient function introduced in Python 3.7 that captures the standard output and error streams of a subprocess. It allows you to run a command and retrieve the output directly, making it easier to programmatically process and manipulate the results.

How to use subprocess.capture_output

Using subprocess.capture_output is straightforward. You first need to import the subprocess module:

import subprocess

To execute a command and capture the output, you can use the subprocess.capture_output function:

result = subprocess.capture_output(['command', 'arg1', 'arg2'], text=True)

In the above example, 'command' is the command you want to execute, 'arg1' and 'arg2' are the optional arguments you want to pass to the command. The text=True argument tells subprocess.capture_output to return the output as a string.

The result variable will then contain the captured output, which you can further process or display as needed.

Example Usage

Let’s say you want to capture the output of the ls command in a Unix-like system. Here’s how you can do it with subprocess.capture_output:

import subprocess

result = subprocess.capture_output(['ls', '-l'], text=True)

print(result.stdout)

In this example, result.stdout will contain the captured output of the ls -l command.

Handling Errors

It’s worth noting that using subprocess.capture_output only captures the output of the subprocess and not any errors that might occur during execution. If you want to capture errors as well, you can use subprocess.run instead, which provides more control over handling errors.

Conclusion

subprocess.capture_output is a helpful addition to the Python subprocess module, allowing you to easily capture the output of subprocesses. It simplifies the process of executing commands and retrieving their results programmatically. By using this function, you can enhance the functionality of your Python scripts when interacting with external programs or system commands.

Remember to import subprocess to use this function, and you’re ready to capture output in your Python code.