What is stderr python

How to understand sys.stdout and sys.stderr in Python

After searching, I found that sys.stdin, sys.stdout, and sys.stderr are file objects corresponding to the interpreter’s standard input, standard output and standard error streams. So, my guess here is that we first assign the sys.stdout and sys.stderr to the variables stdout and stderr. Then, even if there are exceptions in the try statement, can we always get the sys.stdout back? Is this correct? I felt that I was still confused.

1 Answer 1

In normal C programs, there are three «files» open by default: stdin, stdout, and stderr. When you do input and output in C, by default they come from stdin and stdout. But, you can also use them where code expects files, or reassign them to be new files.

Python seeks to «mimic» this behavior of C. When you print() in Python, your text is written to Python’s sys.stdout . When you do input() , it comes from sys.stdin . Exceptions are written to sys.stderr .

You can reassign these variables in order to redirect the output of your code to a file other than stdout. This is very similar to shell redirection, if you’re familiar with that. The reason you might do something like this is to keep a log of your program’s output or make code «shut up», i.e. not send output to stdout. So, in your example example:

stdout = sys.stdout try: sys.stdout = open('file.txt', 'w') print('blah') # etc finally: sys.stdout.close() # close file.txt sys.stdout = stdout sys.stderr = stderr 

This code wouldn’t print anything to the console, but it would write «blah» to a text file named file.txt . To make this sort of thing less error-prone, Python provides sys.__stdin__ and sys.__stdout__ , which always hold the original values of sys.stdin and sys.stdout . The above code could be made simpler using this:

try: sys.stdout = open('file.txt', 'w') print('blah') # etc finally: sys.stdout.close() # close file.txt sys.stdout = sys.__stdout__ 

The reason Python has both stdout and __stdout__ is mainly for convenience, so you don’t have to make a variable to back up stdout .

However, I have to recommend that you don’t make a habit out of reassigning stdout . It’s pretty easy to mess things up that way! If you want to save your code’s output, you can use shell redirection. If you want to have the ability to keep a log of what your program is doing, see Python’s logging module. If you want your code to be quieter, give your functions a quiet=False parameter so you can shut them up when you want! There is rarely a «genuine» need to do reassign stdout , etc. Python allows you to do it, because Python gives programmers a lot of control, and expects them to be responsible. You could do something like this, if you really wanted to:

>>> import random >>> random.random = lambda: 1 >>> random.random() 1 >>> random.random() 1 

Источник

Читайте также:  Удаление фона изображения python

Python — stdin, stdout и stderr

Прежде чем читать эту статью, давайте разберемся, что такое термины stdin , stdout и stderr .

Стандартный ввод — это дескриптор файла, который пользовательская программа читает, чтобы получить информацию от пользователя. Мы передаем ввод на стандартный ввод (stdin).

Стандартный вывод — программа пользователя записывает обычную информацию в этот дескриптор файла. Вывод возвращается через стандартный вывод (stdout).

Стандартная ошибка — программа пользователя записывает информацию об ошибке в этот дескриптор файла. Ошибки возвращаются через стандартную ошибку (stderr).

Python предоставляет нам файловые объекты, представляющие stdin, stdout и stderr. Давайте посмотрим, как мы могли бы работать с этими объектами, чтобы использовать ввод и вывод программы.

1. sys.stdin

Модуль Python sys предоставляет нам все три файловых объекта для stdin, stdout и stderr. В качестве объекта входного файла мы используем sys.stdin . Это похоже на файл, где вы можете открывать и закрывать его, как и любые другие файлы в Python.

Давайте разберемся на простом примере:

import sys stdin_fileno = sys.stdin # Keeps reading from stdin and quits only if the word 'exit' is there # This loop, by default does not terminate, since stdin is open for line in stdin_fileno: # Remove trailing newline characters using strip() if 'exit' == line.strip(): print('Found exit. Terminating the program') exit(0) else: print('Message from sys.stdin: ---> <> <---'.format(line))
Hi Message from sys.stdin: ---> Hi Hello from AskPython 

Выше фрагмент кода продолжает чтение входных данных из stdin и выводит сообщение на консоли ( stdout ) до тех пор , слово exit не встречаются.

Примечание. Обычно мы не закрываем объект файла stdin по умолчанию, хотя это разрешено. Итак, stdin_fileno.close() — допустимый код Python.

Теперь, когда мы немного знаем о stdin , перейдем к stdout .

2. sys.stdout

В качестве объекта выходного файла мы используем sys.stdout . Он похож на sys.stdin , но напрямую отображает все, что написано в нем, в консоли.

В приведенном ниже фрагменте показано, что мы получаем вывод в консоль, если пишем в sys.stdout .

import sys stdout_fileno = sys.stdout sample_input = ['Hi', 'Hello from AskPython', 'exit'] for ip in sample_input: # Prints to stdout stdout_fileno.write(ip + '\n')
Hi Hello from AskPython exit

3. sys.stderr

Это похоже на sys.stdout потому что он также sys.stdout непосредственно выводит в консоль. Но разница в том, что он печатает только сообщения об исключениях и ошибках. (Вот почему он называется стандартной ошибкой).

Проиллюстрируем это на примере.

import sys stdout_fileno = sys.stdout stderr_fileno = sys.stderr sample_input = ['Hi', 'Hello from AskPython', 'exit'] for ip in sample_input: # Prints to stdout stdout_fileno.write(ip + '\n') # Tries to add an Integer with string. Raises an exception try: ip = ip + 100 # Catch all exceptions except: stderr_fileno.write('Exception Occurred!\n')
Hi Exception Occurred! Hello from AskPython Exception Occurred! exit Exception Occurred!

Как вы можете заметить, для всех входных строк мы пытаемся добавить к Integer, что вызовет исключение. Мы перехватываем все такие исключения и печатаем еще одно сообщение отладки с помощью sys.stderr .

Перенаправление в файл

Мы можем перенаправить дескрипторы файлов stdin , stdout и stderr в любой другой файл (дескриптор файла). Это может быть полезно, если вы хотите регистрировать события в файле без использования какого-либо другого модуля, такого как Logging.

Приведенный ниже фрагмент перенаправляет вывод ( stdout ) в файл с именем Output.txt .

Итак, мы не увидим ничего, напечатанного в консоли, потому что теперь это печатается в самом файле! В этом суть перенаправления вывода. Вы «перенаправляете» вывод в другое место. (На этот раз в Output.txt , а не в консоль)

import sys # Save the current stdout so that we can revert sys.stdou after we complete # our redirection stdout_fileno = sys.stdout sample_input = ['Hi', 'Hello from AskPython', 'exit'] # Redirect sys.stdout to the file sys.stdout = open('Output.txt', 'w') for ip in sample_input: # Prints to the redirected stdout (Output.txt) sys.stdout.write(ip + '\n') # Prints to the actual saved stdout handler stdout_fileno.write(ip + '\n') # Close the file sys.stdout.close() # Restore sys.stdout to our old saved file handler sys.stdout = stdout_fileno
root@ubuntu:~# python3 output_redirection.py Hi Hello from AskPython exit root@ubuntu:~# cat Output.txt Hi Hello from AskPython exit

Как видите, мы распечатали вывод как в консоль, так и в Output.txt .

Сначала мы сохраняем исходный sys.stdout обработчик файла sys.stdout в другую переменную. Нам это нужно не только для восстановления sys.stdout в старом обработчике (указывающем на консоль), но мы также можем печатать на консоль, используя эту переменную!

Обратите внимание, что после записи в файл мы закрываем его, аналогично тому, как мы закрываем файл, потому что этот файл все еще был открыт.

Наконец, мы восстанавливаем обработчик sys.stdout в консоли, используя переменную stdout_fileno .

Аналогичный процесс можно выполнить для перенаправления ввода и ошибок, заменив sys.stdout на sys.stdin или sys.stderr и работая с sys.stderr и исключениями вместо вывода.

Источник

How to Print to the Standard Error Stream in Python

Standard streams allow a program to interact with its environment during execution. This could be accepting input from the keyboard (using the input() function in Python), or displaying a message on the screen (using the print() function). There are three standard streams in computing: standard input, standard output, and standard error; they are commonly referred to as stdin, stdout, and stderr, respectively. The sys module allows you to access these streams in Python.

For those of you who are new to Python, our Python Basics course uses interactive exercises to teach you the fundamentals of computer programming. Or check out the Learn Programming with Python track, which bundles several beginner-friendly courses. Following either of these paths will help you learn Python faster.

What Is Python’s Standard Error Stream?

Standard error is an output stream which can be printed to the screen or redirected to a log file. This means any error messages can be analyzed to understand the cause of any bugs. It is independent of the standard output and can be redirected separately.

There are several ways to print to standard error in Python. We will discuss them below, giving you another tool to help you think like a Python developer.

3 Ways to Print to the Standard Error Stream in Python

1. Print to stderr Using print()

The first method to print to standard error is to use the built-in print() function. We have an article describing all you need to know about Python’s print() function; you can refer to it for additional details. For now, here’s an example of using print() :

>>> import sys >>> print('Error message', file=sys.stderr)

Here we used the optional argument file to redirect the output to standard error. By default, the output from the print() function would be directed to standard output. If you want to save a little bit of typing, you can define your own function:

>>> def print_error(*args, **kwargs): . print(*args, file=sys.stderr, **kwargs)

Then you can run the function as follows:

You can also specify additional keyword arguments to give to the print() statement. The end keyword allows you to define what gets printed at the end of the output:

>>> print_error('Error message', end=', good luck debugging me!')
Error message, good luck debugging me!

2. Printing to stderr Using sys.stderr.write()

The second common method to print to standard error in Python doesn’t rely on the print() function; it uses sys.stderr.write(). Here’s an example:

>>> sys.stderr.write('Error message\n')

The function displays the error message and returns an integer. Returning the integer only occurs when the function is executed in the interactive Python console; it represents the length of the string. The newline character ( '\n' ) counts as one character, and is included here because sys.stderr.write() doesn’t move to a new line after displaying the text.

3. Printing to stderr Using logging

The last method uses the logging module, which has functions to help you log events during your programs’ execution. By default, this module prints messages to standard error. You can import the library and log a warning as follows:

>>> import logging >>> logging.basicConfig(format='%(message)s') >>> log = logging.getLogger(__name__) >>> log.warning('Error message')

Here we configure the format of the output, instantiate a logger object with the variable __name__ , and log a warning. This is the output:

This logs the error message with level WARNING. There are other functions which allow you to log errors at different levels and have much more functionality. Check out Python’s documentation for more details.

Use Python’s Standard Error Stream to Work Smarter

In this article, we presented several methods to print to Python’s standard error stream. Remember, this stream is independent of standard output. By taking advantage of the standard error stream, you will ensure there’s little chance of your program crashing before errors are logged – which is a dangerous way for your programs to end. Logging errors properly makes debugging programs easier.

Источник

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