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

In Python, the subprocess module provides a way to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. One useful feature of this module is the ability to redirect standard input/output to a subprocess using subprocess.PIPE.

What is subprocess.PIPE?

subprocess.PIPE is a constant provided by the subprocess module. When used as an argument for stdin, stdout, or stderr parameters in the subprocess.Popen class, it establishes a pipe object to communicate with the standard input/output/error of a subprocess.

By using subprocess.PIPE, you can programmatically interact with the input/output of a subprocess, allowing you to automate tasks, read input from files, or capture output for further processing.

Example Usage

Let’s explore some examples to understand how to use subprocess.PIPE for standard input/output redirection.

Example 1: Reading Standard Output

import subprocess

# Run a shell command and capture the output
result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE, text=True)

# Display the captured output
print(result.stdout)

In this example, we use subprocess.PIPE to capture the standard output of the ls -l command. We then access the captured output using result.stdout and print it.

Example 2: Writing Standard Input

import subprocess

# Run a shell command and provide input
result = subprocess.run(['grep', 'word'], stdin=subprocess.PIPE, text=True)

# Provide input to the subprocess
result.stdin.write('This is a sample line with the word.\n')
result.stdin.close()

# Display the captured output
print(result.stdout)

In this example, we use subprocess.PIPE to provide input to the grep command. We write the input to result.stdin and close it. Finally, we access the captured output using result.stdout and print it.

Conclusion

The subprocess.PIPE feature in Python’s subprocess module makes it easy to redirect standard input/output to a subprocess and interact with it programmatically. It is a powerful tool for automating tasks, processing input/output, and integrating external commands into your Python applications.