[파이썬] subprocess `subprocess.stdin`: 표준 입력 처리

In Python, the subprocess module provides a way to interact with system processes. One of the commonly used features of this module is handling input and output streams. In this blog post, we will focus on the subprocess.stdin attribute, which allows us to handle standard input in subprocesses.

What is subprocess.stdin?

subprocess.stdin is a file-like object that represents the standard input stream of a subprocess. It allows you to pass input to a subprocess and interact with it. By default, this object is connected to the standard input of the parent process.

Using subprocess.stdin

To use subprocess.stdin, you first need to create a subprocess using the subprocess module. You can do this by calling the subprocess.Popen() function and specifying the command you want to execute.

Here is an example that demonstrates how to handle standard input using subprocess.stdin:

import subprocess

# Create a subprocess
process = subprocess.Popen(['python'], stdin=subprocess.PIPE)

# Pass input to the subprocess
process.stdin.write(b'print("Hello, world!")\n')
process.stdin.flush()

# Close the input stream
process.stdin.close()

# Wait for the process to complete
process.wait()

In the above example, we create a subprocess using the subprocess.Popen() function and pass a list containing the command to execute (python in this case). We also specify the stdin argument as subprocess.PIPE, which redirects the standard input of the subprocess to a pipe.

Next, we use the write() method of subprocess.stdin to pass input to the subprocess. In this case, we write the code print("Hello, world!") followed by a newline character. The flush() method ensures that the input is immediately sent to the subprocess.

After passing the input, we close the input stream using the close() method of subprocess.stdin. Finally, we use the wait() method of the subprocess object to wait for the process to complete.

Conclusion

In this blog post, we explored how to handle standard input in subprocesses using subprocess.stdin in Python. This feature is useful when you need to interact with external processes and pass input to them programmatically. Understanding and utilizing subprocess.stdin can greatly enhance your ability to work with subprocesses in Python.

Feel free to experiment with different commands and inputs to explore the full capabilities of subprocess.stdin. Happy coding!