There are a number of ways of taking input in Python, most commonly through the input() function. However, for some use cases you may prefer other methods which work slightly differently. One of these other methods is the Python stdin, which is a part of the sys
module.
The unique feature about stdin is that it allows you to take input directly from the command prompt. You’ll find these options useful on Linux systems in particular.
Using Python Stdin
The first thing to do is import sys from the standard library.
import sys
The stdin automaticlly adds a “\n” newline character after taking input from the user.
There are several ways we can use sys.stdin, so let’s take a look at them one by one.
import sys
for line in sys.stdin:
print(line)
The above technique allows you to continuously input data into the Python Program from the command prompt or IDE. All you have to do is press enter for every line/word you wrote to be sent back to the program.
This technique is a bit tricky, but it’s a pretty useful way of taking input. It can accept multiple lines, without the need to enter them in one by one. If you press enter, it will submit the data, rather it will simply move to the next line.
You can only break out of this loop when the CTRL + D keys are pressed. (Some of you may have to use CTRL + Z, depending on your OS setup)
Alternatively, you can do the following:
import sys
for line in sys.stdin:
if 'exit' == line.rstrip():
break
print(line)
If the word “exit” is entered, then the loop will be broken.
This is similar to the first technique, but instead it reads a whole block of data at once, instead of line by line.
import sys
inp = sys.stdin.read()
print(inp)
Similarly to the previous technique, you can only break out of this when CTRL + D keys are pressed.
Here’s another way of taking input which is useful for counting the number of lines entered. It takes each line and stores it into a list, which it returns back to the program.
import sys
inp = sys.stdin.readlines()
print(len(inp))
print(inp)
Here is the input and the corresponding output for the above code. “Hello World” was the input that we split across two lines, and the last two lines show the output.
Hello
World
2
['Hello \n', 'World\n']
This marks the end of the Python Stdin Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content can be asked in the comments section below.