[파이썬] subprocess `subprocess.text`: 텍스트 모드 설정

When using subprocess.run(), you can pass additional arguments to customize the behavior of the subprocess. One such argument is text, which allows you to specify whether the input and output of the subprocess should be treated as text.

By default, text is set to False, which means that the input and output are treated as bytes. However, you can change it to True to enable text mode. In text mode, the input and output of the subprocess are treated as strings.

Here’s an example that demonstrates how to use the text argument in subprocess.run():

import subprocess

# Run a command and capture its output as text
result = subprocess.run(['ls', '-l'], text=True, capture_output=True)

# Print the output
print(result.stdout)

In the above example, we run the ls -l command using subprocess.run() with text set to True. This means that the output of the subprocess will be treated as text. The capture_output parameter is also set to True to capture the output in the result object.

We can then access the captured output through the stdout attribute of the result object and print it. Since stdout is treated as text, we can directly print it without decoding it from bytes.

Using the text mode in subprocess is helpful when you want to work with text-based processes and manipulate their output as strings. It simplifies the process of handling input and output, allowing you to focus on the logic of your program.