[파이썬] `sys.__stdin__`: 원본 표준 입력 스트림

In Python, the sys module provides access to system-specific parameters and functions. One of the attributes in this module is sys.__stdin__, which represents the original standard input stream.

The standard input stream is a way to receive input from the user or from another program. It is commonly used when reading data from the keyboard or when redirecting input from a file.

With sys.__stdin__, you can interact with the standard input stream to read input and collect user data.

Reading Input from sys.__stdin__

To read input from sys.__stdin__, you can use the readline() method. This method reads a line from the input stream and returns it as a string. Here’s an example:

import sys

# Read a single line from the standard input stream
line = sys.__stdin__.readline()

# Print the input
print("Input:", line)

In the above code, the readline() method is called on sys.__stdin__ to read a line from the standard input stream. The line is then printed using the print() function.

Redirecting Input

The standard input stream can be redirected to read input from a file instead of the keyboard. This can be useful when testing with predefined input data. To redirect the input, you can use the command line input redirection operators.

For example, if you have a file called input.txt containing the input data, you can redirect the input to read from the file like this:

python script.py < input.txt

In the above command, the < operator redirects the input to read from input.txt, and script.py is the Python script that uses sys.__stdin__ to read the input.

Conclusion

The sys.__stdin__ attribute in Python provides access to the original standard input stream. You can use it to read input from the user or redirect input from a file. This is a powerful tool for collecting user data and automating tasks that require input interaction.

Remember to use the appropriate methods, like readline(), to read input from sys.__stdin__. Experiment with redirecting input to test your code with different input scenarios.

So, try using sys.__stdin__ in your Python programs to handle input effectively and efficiently!