How to Read From stdin in Python

Published on Aug. 22, 2023, 12:16 p.m.

To read from standard input (stdin) in Python, you can use the built-in input() function, which reads input from standard input as a string. Here’s an example of how to use it:

user_input = input("Please enter some input: ")
print("You entered:", user_input)

In this example, the input() function will block the execution of the program, and wait for the user to input some text followed by a newline character. The text input will then be assigned to the variable user_input, which we can then use or manipulate in the program as needed.

Alternatively, you can also use the sys.stdin module to read from standard input by calling the readline() or read() method. Here’s an example using sys.stdin:

import sys

line = sys.stdin.readline()
print("You entered:", line)

In this example, the readline() method will block the execution of the program, and wait for the user to input some text followed by a newline character. The text input will then be assigned to the variable line, which can be used or manipulated in the program.

Tags:

related content