深度阅读

How to Read From stdin in Python

作者
作者
2023年08月22日
更新时间
10.74 分钟
阅读时间
0
阅读量

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.

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。