Reading standard input python

Как читать данные из стандартного ввода в Python

Есть три способа чтения данных из стандартного ввода в Python:

1. Использование sys.stdin для чтения со стандартного ввода

Python sys module stdin используется интерпретатором для стандартного ввода. Внутри он вызывает функцию input(). К входной строке в конце добавляется символ новой строки (\ n). Итак, вы можете использовать функцию rstrip(), чтобы удалить его.

Вот простая программа для чтения пользовательских сообщений из стандартного ввода и их обработки. Программа завершится, когда пользователь введет сообщение «Выход».

import sys for line in sys.stdin: if 'Exit' == line.rstrip(): break print(f'Processing Message from sys.stdin **********') print("Done")
Hi Processing Message from sys.stdin *****Hi ***** Hello Processing Message from sys.stdin *****Hello ***** Exit Done

Пример Stdin в Python

Обратите внимание на использование rstrip() для удаления завершающего символа новой строки, чтобы мы могли проверить, ввел ли пользователь сообщение «Exit» или нет.

2. Использование функции input() для чтения данных stdin

Мы также можем использовать функцию input() для чтения стандартных входных данных. Мы также можем запросить сообщение пользователю.

Вот простой пример чтения и обработки стандартного входного сообщения в бесконечном цикле, если пользователь не вводит сообщение Exit.

while True: data = input("Please enter the message:\n") if 'Exit' == data: break print(f'Processing Message from input() **********') print("Done")

Ввод считывается из Stdin в Python

Функция input() не добавляет в сообщение пользователя символ новой строки.

3. Чтение стандартного ввода с использованием модуля ввода файлов

Мы также можем использовать функцию fileinput.input() для чтения из стандартного ввода. Модуль fileinput предоставляет служебные функции для перебора стандартного ввода или списка файлов. Когда мы не предоставляем никаких аргументов функции input(), она считывает аргументы из стандартного ввода.

Эта функция работает так же, как sys.stdin, и добавляет символ новой строки в конец введенных пользователем данных.

import fileinput for fileinput_line in fileinput.input(): if 'Exit' == fileinput_line.rstrip(): break print(f'Processing Message from fileinput.input() **********') print("Done")

Источник

How to Read from stdin in Python

How to Read from stdin in Python

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Читайте также:  Python xlrd количество строк

1. Using sys.stdin to read from standard input

Python sys module stdin is used by the interpreter for standard input. Internally, it calls the input() function. The input string is appended with a newline character (\n) in the end. So, you can use the rstrip() function to remove it. Here is a simple program to read user messages from the standard input and process it. The program will terminate when the user enters “Exit” message.

import sys for line in sys.stdin: if 'Exit' == line.rstrip(): break print(f'Processing Message from sys.stdin **********') print("Done") 
Hi Processing Message from sys.stdin *****Hi ***** Hello Processing Message from sys.stdin *****Hello ***** Exit Done 

Python Stdin Example

Notice the use of rstrip() to remove the trailing newline character so that we can check if the user has entered “Exit” message or not.

2. Using input() function to read stdin data

We can also use Python input() function to read the standard input data. We can also prompt a message to the user. Here is a simple example to read and process the standard input message in the infinite loop, unless the user enters the Exit message.

while True: data = input("Please enter the message:\n") if 'Exit' == data: break print(f'Processing Message from input() **********') print("Done") 

Python Input Read From Stdin

The input() function doesn’t append newline character to the user message.

3. Reading Standard Input using fileinput module

We can also use fileinput.input() function to read from the standard input. The fileinput module provides utility functions to loop over standard input or a list of files. When we don’t provide any argument to the input() function, it reads arguments from the standard input. This function works in the same way as sys.stdin and adds a newline character to the end of the user-entered data.

import fileinput for fileinput_line in fileinput.input(): if 'Exit' == fileinput_line.rstrip(): break print(f'Processing Message from fileinput.input() **********') print("Done") 

Python Fileinput Read Standard Input

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

Best Ways to Read Input in Python From Stdin

python read input from stdin

When you are writing a python code, the most basic and essential thing is data. Data on which you can perform mathematical and arithmetic operations to finally get the results you desire. However, to perform these operations, you need to input the data into your code. Although there are various ways you can input data in your code, we are going to specifically cover information about python read input from stdin.

What Is Stdin?

Best Ways to Read Input in Python From Stdin

Stdin is standard input. Standard input is basically a stream that creates a file in which it stores inputs from which the program can access the input data and write output accordingly. Additionally, there are many ways you can read input from stdin in python programming. We will cover those methods in this article.

Read Input From Stdin Using Input()

In the first method, we will see how we can read standard input using the ‘input()’ function. Taking input using the ‘input()’ function is quite simple. Let’s directly understand the syntax and usage of the function with the help of an example:

x = input("write your input: ") #define a variable to store input in print(x) #print the variable to get output in form of input string, variable or float.
write your input: Hello world Hello world

In the above example, we use a variable in which we store the input and print that variable to print the stored input. We can also perform mathematical and arithmetic operations on this variable if the input form is an integer or any other computable form.

Читайте также:  Создаем css стиль кнопок

Read Input From Stdin Using Sys Module

The sys module offers many functions, one of which is ‘sys.stdin()’. Again let’s understand better with the help of an example:

import sys for line in sys.stdin: if 'Exit' == line.rstrip(): break print(f'The input entered : ') print("Program Exited")
Hello The input entered : Hello Welcome to python pool The input entered : Welcome to python pool Exit Program Exited

In this example we use ‘sys.stdin’ function which internally calls ‘input()’ function. Moreover, ‘sys.stdin’ takes new line input after every sentence. In addition to that, we have used the ‘rstrip()’ function, which checks if the user has entered Exit as an input string or not. If the user enters Exit as an input, it stops the program. Furthermore, ‘sys.stdin’ is case sensitive, so the string you set as your exit string should match the input string case-wise too.

Read Input From Stdin Using Fileinput Module

Fileinput module can read and write multiple files from stdin. It takes files as an argument and returns text present in it. Besides that, you can also read and write other formats of files. Again let’s understand the usage and syntax of this module.

import fileinput for line in fileinput.input(): print(line)
testdataa.txt This a sample text file

This example shows a simple implementation of fileinput module in which we use the ‘fileinput.input()’ function to read stdin input. Further, if you want to know how to read a file line by line, check out this post.

Read Binary Input Data From Stdin

Sometimes you may require to read a file containing binary data. You can use three modules side by side to read stdin of binary form. The following three modules are os, sys, and msvcrt. To understand how to read binary data from stdin, let’s see an example.

import os, sys, msvcrt msvcrt.setmode (sys.stdin.fileno(), os.O_BINARY) input = sys.stdin.read('testdata1.bin') print len (input)

We use three modules to read binary files from the standard input sys module is used for taking stdin, the os module is used for reading files in binary format, and finally, the msvcrt module is used to set the line-end translation mode for the file descriptor.

Читайте также:  Команда выхода из python

Sys.readline Reading From Stdin

The ‘sys.readline()’ is a function offered by the sys module. It can read lines from the stdin stream. In addition to that, this function can read the escape character. Moreover, we can also set the parameter to read characters, meaning we can set the function to read a specific amount of characters from the input. Let us see an example to see how we can use this function.

import sys inputone = sys.stdin.readline() print(inputone) inputtwo = sys.stdin.readline(4) print(inputtwo)
Hello Hello\n Welcome Welc

As you can see in input one, there is a space after “Hello “ the readline function identifies that escape character and prints it. Further in input-two, the parameter to read characters is set to four. Therefore, it only reads four characters from the input.

Read Input From Stdin Line By Line

You can also read input from stdin line by line. To achieve this, you can use the sys module and ‘sys.stdin.readlines()’ function.

import sys data = sys.stdin.readlines()

The above code shows how you can use the ‘sys.stdin.readlines()’ function and how its syntax is defined.

Read Stdin Until Specific Character

Sometimes you might want to read standard input until a specific character, like any specific integer or a string, to do that. You can use the sys module and create a loop that terminates when we enter a specific character. Let’s take an example to understand this.

import sys def read_until_character(): x = [ ] minus = False while True: character = sys.stdin.read(1) if not character: break if character == '2' and minus: x.pop() break else: minus = (character == '-') x.append(char) return ''.join(buf) print(read_until_character())
11 21 34 -23 22 -11 2 11 21 34

As you can see in this example, our code reads input until we enter the -2 character and prints the output up to the previous character of -2.

FAQs on Python Read Input from Stdin

Stdin is standard input. Read from standard input means sending data to a stream that is used by the program. It is a file descriptor in Python.

You can use fileinput module and use fileinput.input function to read one or more text files at the same time.

To read from stdin, you can use one of three methods: sys.stdin, ‘input()’ function, or fileinput module.

You can use ‘sys.readline()’ function to read the escape characters, and further, you can also define the parameter to read characters.

Conclusion

Finally, we can conclude that there are many ways you can read input from standard input (stdin). You can use any of the methods as per your requirements for the program. Moreover, you can use these methods and develop your own logic because you can use the functions we have discussed creatively and efficiently to achieve your desired results.

Источник

Оцените статью