Print error to file python

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.

Читайте также:  Php include get запрос

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.

Источник

print to stderr python

In this article, we will discuss how you can print to stderr in Python. Stderr is a standard error stream that we use when we want to print error messages. Therefore if you want to output or print error messages, you can print them to stderr. There are many ways you can print to stderr, and we will discuss those methods in this article one after the other.

Using Logging Module

Using Logging Module in Stderr

The logging module in Python keeps a log of messages. Further, we can use this module to print to stderr in Python by configuring some settings of the module. To print to stderr using logging module eventually you will need to use some functions of logging module they are as follows:

  • ‘logging.basicConfig()’ function , this function takes the format of the message as an input parameter.
  • ‘logging.getLogger()’ this function is used for returning objects from logging module.
  • ‘log.warning()’ this function takes the warning message text and prints it to the standard output.

However, you need to use these functions in combination with each other to print your desired error message. Let’s understand with the help of an example.

import logging logging.basicConfig(format = '%(messages)s') log = logging.getLogger() log.warning('ERROR!')

You can also use an alternative way by using the sys module and logging module both and in addition to that by using the ‘print()’ function and setting the parameter in the ‘print()’ function.

import logging import sys logging.basicConfig(format = '%(messages)s') log = logging.getLogger() print(log, file = sys.stderr)

The sys module provides many functions, and one of them is ‘sys.stderr.write()’, which we can use to print error messages. To print to stderr in Python using the ‘sys.stderr.write()’ function, you have to follow its syntax usage. To understand the syntax and usage of this function, let us see an example.

import sys sys.stderr.write("ERROR!")

As you can see, using the sys module to print to standard error is pretty simple and straightforward.

And to learn more about libraries in Python, check this post.

We can also use the ‘print()’ function to print to stderr in Python. Although for printing to standard error using the ‘print()’ function, first we need to set this function’s parameter. To change the parameter, we will use the sys module, which offers many functions. Eventually, we will use sys.stderr to change the parameter of the ‘print()’ function.

import sys print("ERROR", file = sys.stderr)

You can also ‘print()’ function to print string variables to stderr in Python. In order to do that, first, you need to assign a variable to a string you want to print to standard error and then print the following variable.

import sys x = "ERROR MESSAGE" print(x, file = sys.stderr)

Further, you can also print a string which you take from user input and print to stderr in Python.

import sys x = input("Enter the string you want to print to stderr: ") print(x, file = sys)
Enter the string you want to print to stderr: ERROR MESSAGE ERROR MESSAGE

In addition to this, you can also print a variable containing a list to standard error. Let us take an example to furthermore understand how.

import sys x = ["This", "Is", "Error"] print(x, file = sys.stderr)

You can also create a function that prints to standard error. The advantage of creating a special function is that if you want to print to standard error frequently, you will not need to use the ‘print()’ and ‘write()’ functions again and again. Nonetheless, the special function will do that for you. In order to understand better, let us use an example.

import sys def error(error_message): print(error_message, file=sys.stderr)

As you can see in this special function, too, we use the ‘print()’ function and sys module and its corresponding ‘sys.stderr’ function. We call the function to print to stderr in Python. Further, you can also use this function to print strings and lists by calling this function.

Similarly, we can use this function to print a variable that contains the string. Again let us take an example to understand.

Further you can also use this function to print a variable that contains list. The function will print that list to stderr in Python.

x = ["ERROR MESSAGE!", "THIS IS EXAMPLE"] error(x)
["ERROR MESSAGE!", "THIS IS EXAMPLE"]

And even furthermore, you can use this function to print to stderr in Python the inputs you take from the user. To do the following, you first need to store the input in a variable and then print that variable through the function we have made.

x = input("Enter the message you want to print to stderr: ") error(x)
Enter the message you want to print to stderr: ERROR MESSAGE! ERROR MESSAGE!

Write Stderr To File

We can also write standard errors to a file in Python. In order to do the following, we need to again use the sys module. Firstly we will assign the path of the file to a variable and then use the ‘sys.stderr’ function to open that path and the ‘print()’ function to write the error message or string in that file. Let us see an example of this method.

import sys pathvariable = 'path/to/yourfile.txt' sys.stderr = open(path, 'w') print("ERROR MESSAGE")

in the above code, we use the ‘open()’ function and give ‘w’ as a parameter to write in that file.

Exit After Printing To Stderr

Sometimes you might want to exit the program after printing to stderr. In order to do that, you need to import the sys module and use the ‘sys.exit()’ function after printing to stderr in Python. Eventually, let’s understand better with the help of an example.

import sys print("ERROR", file = sys.stderr) sys.exit(1)

Although there is also an alternative method you can use to exit the program after printing to stderr in Python.

import sys print("ERROR MESSAGE", file = sys.stderr) raise SystemExit(1)

In the latter method, we raise an exception called ‘SystemExit.’ When we raise this exception, the top-level interpreter in the compiler senses this special class exception and follows the exit routine of this exception. If you notice, we have written ‘(1)’ as a parameter in this special class exception. The reason for this is that ‘SystemExit’ takes integers as a parameter for exiting the code. Therefore we use an integer as a parameter to exit the code.

FAQs

Stderr is a standard error stream in Python that we can use to display error messages.

Printing to stderr means that you can display error messages on the terminal or the output terminal.

You can use various methods discussed in this article which include functions like ‘sys.write()’, ‘print()’, and even more, you can also create your own function to print to stderr in Python.

Conclusion

To summarize this article, we can say that there are many methods you can use to print to stderr in Python, which includes many functions like ‘write()’, ‘print()’. Furthermore, we have also discussed how we can create our own function to print to stderr in Python. You can use the following functions as per your needs of the code and how your code allows you to use them.

Источник

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