[파이썬] subprocess `subprocess.universal_newlines=True`: 텍스트 모드로 입출력

In today’s blog post, we will explore how to use the subprocess module in Python to perform input/output operations in text mode.

Introduction

The subprocess module provides a way to create new processes, connect to their input/output/error pipes, and obtain their return codes. By default, subprocess works in binary mode, which means it expects and produces byte strings. However, we can use the universal_newlines=True argument to enable text mode, allowing us to work with string data directly.

Getting Started

To get started, let’s import the subprocess module:

import subprocess

Enabling Text Mode

To enable text mode in subprocess, we need to set the universal_newlines parameter to True when creating a Popen object. This ensures that the input/output data is treated as text rather than binary.

Here’s an example of how to use subprocess in text mode:

# Set up the command
command = ["echo", "Hello, World!"]

# Create the subprocess in text mode
process = subprocess.Popen(command, stdout=subprocess.PIPE, universal_newlines=True)

# Read the output
output = process.communicate()[0]

# Print the output
print(output)

In the above example, we use the Popen class to create a subprocess that runs the echo command with the argument “Hello, World!”. The universal_newlines=True argument ensures that the output from the subprocess is treated as a text string rather than binary data. We then use the communicate() method to capture the output of the subprocess and assign it to the output variable. Finally, we print the output.

Conclusion

Using subprocess in text mode allows us to easily handle input/output operations with string data. By setting universal_newlines=True, we can work with text data directly, making it more convenient and flexible.

In this blog post, we’ve covered the basics of using subprocess in text mode. I hope you found this information helpful and that you can now apply it to your own projects. Stay tuned for more interesting topics on Python programming.