Std error 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

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
print to stderr python.

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!')

Output:

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)

Print To Stderr Using Sys Module

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!")

Output:

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.

“Other Commands Don’t Work After on_message” in Discord Bots

Print To Stderr Using Print() Function

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.

Let’s see an example.

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

Output:

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)

Output:

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)

Output:

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)

Output:

[“This”, “Is”, “Error”]

Print To Stderr Using Special Function

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.

Output:

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

x = "ERROR MESSAGE!"
error(x)

Output:

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)

Output:

["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)

Output:

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

What is stderr?

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

What does it mean to print to stderr?

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

How do I print a message to stderr in Python?

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.

Trending Python Articles

  • “Other Commands Don’t Work After on_message” in Discord Bots

    “Other Commands Don’t Work After on_message” in Discord Bots

    February 5, 2023

  • Botocore.Exceptions.NoCredentialsError: Unable to Locate Credentials

    Botocore.Exceptions.NoCredentialsError: Unable to Locate Credentials

    by Rahul Kumar YadavFebruary 5, 2023

  • [Resolved] NameError: Name _mysql is Not Defined

    [Resolved] NameError: Name _mysql is Not Defined

    by Rahul Kumar YadavFebruary 5, 2023

  • Best Ways to Implement Regex New Line in Python

    Best Ways to Implement Regex New Line in Python

    by Rahul Kumar YadavFebruary 5, 2023

In Python, whenever we use print() the text is written to Python’s sys.stdout, whenever input() is used, it comes from sys.stdin, and whenever exceptions occur it is written to sys.stderr

We can redirect the output of our code to a file other than stdout. But you may be wondering why one should do this? The reason can be to keep a log of your code’s output or to make your code shut up i.e. not sending any output to the stdout. Let’s see how to do it with the below examples.

 What is Python stderr?

This file handle receives error information from the user program. The Standard error returns errors stderr. we will see different examples of using stderr.

Method 1: Using Python stderr

It is comparable to stdout in that it likewise prints straight to the console, but the key distinction is that it prints only Exceptions and Error messages which is why it is called Standard Error in Python.

Python3

import sys

def print_to_stderr(*a):

    print(*a, file=sys.stderr)

print_to_stderr("Hello World")

Output:

Method 2:  Using Python sys.stderr.write() function

When used in interactive mode, sys.stderr.write() accomplishes the same task as the object it stands for, with the exception that it also prints the text’s letter count.

Python3

import sys

print("Example 1")

print("Example 2", file=sys.stderr)

sys.stderr.write("Example 3")

Output:

Method 3: Using Python logging.warning  function

A built-in Python package tool called logging.warning enables publishing status messages to files or other output streams. The file may provide details about which portion of the code is run and any issues that have come up.

Python3

import logging

logging.basicConfig(format='%(message)s')

log = logging.getLogger(__name__)

log.warning('Error: Hello World')

print('GeeksforGeeks')

Output:

Error: Hello World
GeeksforGeeks

What is Python stdout?

This file handle receives regular information from the user program. The output is made available through the standard output stdout from sys module.

Method 1: Using Python  sys.stdout method

stdout in Python is similar to sys.stdin, but it directly displays anything written to it to the Console.

Python3

import sys

def print_to_stdout(*a):

    print(*a, file=sys.stdout)

print_to_stdout("Hello World")

Output:

Method 2: Using Python print() function

Python print() function prints the message to the screen or any other standard output device. In the print() function, it requires an empty parenthesis at the end that tells Python to execute the function rather than calling it by name. 

Python3

print( "Hello GeeksforGeeks" )

Output:

Hello GeeksforGeeks

Method 3: Using Python sys.stdout.write() function

The sys.stdout.write() serves the same purpose as the object stands for except it prints the number of letters within the text too when used in interactive mode

Python3

import sys

a = 11

print(a)

print(a, file=sys.stdout)

sys.stdout.write(a)

Output:

Introduction

Among the popular operating systems, they have all standardized on using standard input, standard output, and standard error
with file desciptors 0, 1, and 2 respectively. This allows you to pipe the inputs and outputs to different locations.
Let’s look at how to utilize standard input, output, and error in Python.

To learn more about piping, redirection, stdin, stdout, and stderr in general, see my tutorial
STDIN, STDOUT, STDERR, Piping, and Redirecting.

Basic usage

In Python, the sys.stdin, sys.stdout, and sys.stderr are file-like objects that can perform
expected operations like read() and write(). Let’s look at how to use these objects.
Refer to the official sys package documentation for full information.

Standard output

Standard output

print(x) is basically a shortcut for sys.stdout.write(x + 'n')

import sys

# Standard output - sys.stdout
print(type(sys.stdout))
sys.stdout.write('Hellon')

sys.stdout is a io.TextIOWrapper objects so you can read and write to them like a regular file.
See https://docs.python.org/3/library/io.html#io.TextIOWrapper for more details about the io.TextIOWrapper class.

To pipe the output of your Python program to a file, you can do it from the shell like this:

python myapp.py > output.txt

Standard error

Standard error works just like standard output and can be used the same way. Standard error has file descriptor 2 where standard output has file descriptor 1. This is beneficial if you want to separate warning and error messages from the actual output of your application. For example, if your program outputs an XML file, you don’t want error strings injected in the middle of your XML file.

# Standard error - sys.stderr
print(type(sys.stderr))
sys.stderr.write("Error messages can go heren")

To pipe standard error from the shell to a file while leaving standard output going to the terminal:

python myapp.py 2>errors.txt

To pipe standard error in to standard output, you can do:

python myapp.py 2>&1

Standard input

Standard input defaults to your keyboard in the terminal, but you can also pipe in files
or the output from a previous program to your standard input. Here is a basic example
of reading one byte from standard input:

# Standard input - sys.stdin
print(type(sys.stdin))
letter = sys.stdin.read(1)  # Read 1 byte
print(letter)
# Can also do things like `sys.stdin.readlines()`

If you want interactive input from the user, it is better to use input() instead of sys.stdin.read() when asking for user input,
but sys.stdin.readlines() can be useful for reading a file that was piped in from the shell like this:

# Feed `input_file.txt` to `sys.stdin` of the Python script
python my_script.py < input_file.txt

To pipe the standard output of one program to the standard input of your Python program,
you can do it like this:

cat data.txt | python myapp.py

Dunder properties: sys.__stdin__, sys.__stdout__, sys.__stderr__

The dunder properties sys.__stdin__, sys.__stdout__ and sys.__stderr__ always contain references
to the original streams. If you re-assign sys.stdout to point somewhere else like a StringIO object,
you can always assign it back to the original value with the following.

Changing sys.stdout to a StringIO object can be useful especially when unit testing.
Check out my tutorial Python Use StringIO to Capture STDOUT and STDERR.

from io import StringIO
import sys

temp_output = StringIO()

# Replace stdout with the StringIO object
sys.stdout = temp_output
# Now, if you print() or use sys.stdout.write
# it goes to the string objc
print('This is going to the StringIO obecjt.')
sys.stdout.write('This is not going to the "real" stdout, yet')

# Then we can restore original stdout
sys.stdout = sys.__stdout__
print("Contents of the StringIO object")
print("===============================")
print(temp_output.getvalue())

fileinput.input() shortcut

This function will return standard input separated by line, or if file names
were provided as command-line arguments, it will provide all the lines from
the files provided. It is similar to ARGF in Ruby. This gives you the option
to pipe in a file from the shell or to provide a list of file paths for input.

For example, you can either pipe in files via standard input or provide a list of filenames as arguments to the application:

python my_app.py < file1.txt
python my_app.py file1.txt file2.txt file3.txt

Here is an example of it in a script:

# fileinput_example.py
import fileinput

lines_of_data = fileinput.input()
print(type(lines_of_data))  # fileinput.FileInput

# One option: Join each line together to one long string
print(''.join(lines_of_data))

# Another option: Iterate through each line
# for line in lines_of_data:
#     print(line.strip())

Here is how you can run the program to pipe in files or provide file names:

# Pipe file in via stdin
python fileinput_example.py < file1.txt

# Provide list of files as arguments
python fileinput_example.py file1.txt file2.txt file3.txt

Conclusion

After reading this guide, you should know how to access and read/write from standard input, standard output, and standard error in Python. You should also know how to use a StringIO object to capture output, and use the fileinput.input() function to get data.

References

  • sys documentation
  • Python io.TextIOWrapper documentation
  • STDIN, STDOUT, STDERR, Piping, and Redirecting
  • Python Use StringIO to Capture STDOUT and STDERR
  • fileinput.input()

Before going through this article, let us understand what the terms stdin, stdout and stderr are.

Standard input – This is the file-handle that a user program reads to get information from the user. We give input to the standard input (stdin).

Standard output – The user program writes normal information to this file-handle. The output is returned via the Standard output (stdout).

Standard error – The user program writes error information to this file-handle. Errors are returned via the Standard error (stderr).

Python provides us with file-like objects that represent stdin, stdout, and stderr. Let us look at how we could work with these objects to work with the input and output of our program.


1. sys.stdin

Python’s sys module provides us with all three file objects for stdin, stdout, and stderr. For the input file object, we use sys.stdin. This is similar to a file, where you can open and close it, just like any other file.

Let us understand this through a basic example:

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))

Output

Hi
Message from sys.stdin: ---> Hi
 <---
Hello from AskPython
Message from sys.stdin: ---> Hello from AskPython
 <---
exit
Found exit. Terminating the program

The above snippet keeps reading input from stdin and prints the message to the Console (stdout) until the word exit is encountered.

NOTE: We do not normally close the default stdin file object, although it is allowed. So stdin_fileno.close() is valid Python code.

Now that we know a little bit about stdin, let us move to stdout.


2. sys.stdout

For the output file object, we use sys.stdout. It is similar to sys.stdin, but it directly displays anything written to it to the Console.

The below snippet shows that we get the Output to the Console if we write to 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')

Output

Hi
Hello from AskPython
exit

3. sys.stderr

This is similar to sys.stdout because it also prints directly to the Console. But the difference is that it only prints Exceptions and Error messages. (Which is why it is called Standard Error).

Let us illustrate this with an example.

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')

Output

Hi
Exception Occurred!
Hello from AskPython
Exception Occurred!
exit
Exception Occurred!

As you can observe, for all the input strings, we try to add to an Integer, which will raise an Exception. We catch all such exceptions and print another debug message using sys.stderr.


Redirection to a file

We can redirect the stdin, stdout and stderr file handles to any other file (file-handle). This may be useful if you want to log events to a file without using any other module such as Logging.

The below snippet redirects output(stdout) to a file called Output.txt.

So, we will not see anything printed to the Console, because it is now being printed to the file itself! This is the essence of Output redirection. You ‘redirect’ the Output to some other place. (This time, to Output.txt, instead of the Console)

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

Output

As you can see, we have printed the output to both the Console, as well as to Output.txt.

We first save the original sys.stdout file handler object to another Variable. We not only need this to restore sys.stdout to the old handler (pointing to the Console), but we can also print to the console using this Variable!

Note that after writing to the file, we close it, similar to how we close a file because that file was still open.

We finally restore the handler of sys.stdout to the Console, using the variable stdout_fileno.

A similar process can be followed for Input and Error redirection, replacing sys.stdout with sys.stdin or sys.stderr and working with Inputs and Exceptions instead of Output.


Conclusion

In this article, we learned about using stdin, stdout and stderr in Python, using the sys module. We also learned how to manipulate the corresponding file handlers for redirection to/from a file.

References

  • JournalDev article on reading input from stdin
  • StackOverflow question on stdin, stdout, and stderr

In this python tutorial, you will learn about python print – stderr, stdin, and stdout with examples.

Python provides us with file-like objects that represent stdin, stdout, and stderr. So first we need to import the sys module in python. Here we will see how we can work with these objects.

Python print to stderr

Python stderr is known as a standard error stream. It is similar to stdout because it also directly prints to the console but the main difference is that it only prints error messages.

Example:

import sys
sys.stderr.write("This is error msg")

After writing the above code (python print to stderr), you can observe that it print debug message using sys.stderr. Stderr always used for printing errors and it is beneficial if you want to separate warning and error message from the actual output.

You can refer to the below screenshot for python print to stderr.

Python print to stderr
Python print to stderr

Python take input from stdin

Python stdin is used for standard input as it internally calls the input function and the input string is appended with a newline character in the end. So, use rstrip() function to remove it.

Example:

import sys
for line in sys.stdin:
if 'E' == line.rstrip():
break
print(f"Message : {line}')
print("End")

After writing the above code (python take input from stdin), the program reads the user message from standard input and processes it accordingly. The program will terminate when the user will input the “E” message and it prints “End”.

You can refer to the below screenshot for python take input from stdin.

Python take input from stdin
Python take input from stdin

Python stdout is known as standard output. Here, the write function will print directly whatever string you will give.

Example:

import sys
s = sys.stdout
my_input = ['Welcome', 'to', 'python']
for a in my_input:
s.write(a + 'n')

After writing the above code (python stdout), the output will be ” Welcome to python”. We get the output to the console as we write sys.stdout. So, whatever input is given we will see on the console.

You can refer to the below screenshot for python stdout.

Python stdout
Python stdout

Read from stdin in python

To read an input from stdin we can call read() and readlines() function in Python, for reading everything.

Example:

from sys import stdin
my_input = stdin.read(1)
my_input2 = stdin.readline()
total = int(my_input2)
print("my_input = {}".format(my_input))
print("my_input2 = {}".format(my_input2))
print("total = {}".format(total))

After writing the above code (read from stdin in python), the stdin will read input and prints the input for each.

You can refer to the below screenshot for read from stdin in python.

Read from stdin in python
Read from stdin in python

You may like the following Python tutorials:

  • Increment and Decrement operators in Python
  • Object oriented programming python
  • Constructor in Python
  • Python access modifiers + Examples
  • Python Anonymous Function
  • Python Read CSV File and Write CSV File
  • Python Array with Examples
  • Python get filename from the path

In this Python Tutorial, we learned – Python print to stderr, Python takes input from stdin, Python stdout, and Read from stdin in python with example.

Bijay Kumar MVP

Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.


The standard error of the mean is a way to measure how spread out values are in a dataset. It is calculated as:

Standard error of the mean = s / √n

where:

  • s: sample standard deviation
  • n: sample size

This tutorial explains two methods you can use to calculate the standard error of the mean for a dataset in Python. Note that both methods produce the exact same results.

Method 1: Use SciPy

The first way to calculate the standard error of the mean is to use the sem() function from the SciPy Stats library.

The following code shows how to use this function:

from scipy.stats import sem

#define dataset 
data = [3, 4, 4, 5, 7, 8, 12, 14, 14, 15, 17, 19, 22, 24, 24, 24, 25, 28, 28, 29]

#calculate standard error of the mean 
sem(data)

2.001447

The standard error of the mean turns out to be 2.001447.

Method 2: Use NumPy

Another way to calculate the standard error of the mean for a dataset is to use the std() function from NumPy.

Note that we must specify ddof=1 in the argument for this function to calculate the sample standard deviation as opposed to the population standard deviation.

The following code shows how to do so:

import numpy as np

#define dataset
data = np.array([3, 4, 4, 5, 7, 8, 12, 14, 14, 15, 17, 19, 22, 24, 24, 24, 25, 28, 28, 29])

#calculate standard error of the mean 
np.std(data, ddof=1) / np.sqrt(np.size(data))

2.001447

Once again, the standard error of the mean turns out to be 2.001447.

How to Interpret the Standard Error of the Mean

The standard error of the mean is simply a measure of how spread out values are around the mean. There are two things to keep in mind when interpreting the standard error of the mean:

1. The larger the standard error of the mean, the more spread out values are around the mean in a dataset.

To illustrate this, consider if we change the last value in the previous dataset to a much larger number:

from scipy.stats import sem

#define dataset 
data = [3, 4, 4, 5, 7, 8, 12, 14, 14, 15, 17, 19, 22, 24, 24, 24, 25, 28, 28, 150]

#calculate standard error of the mean 
sem(data)

6.978265

Notice how the standard error jumps from 2.001447 to 6.978265. This is an indication that the values in this dataset are more spread out around the mean compared to the previous dataset.

2. As the sample size increases, the standard error of the mean tends to decrease.

To illustrate this, consider the standard error of the mean for the following two datasets:

from scipy.stats import sem 

#define first dataset and find SEM
data1 = [1, 2, 3, 4, 5]
sem(data1)

0.7071068

#define second dataset and find SEM
data2 = [1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
sem(data2)

0.4714045

The second dataset is simply the first dataset repeated twice. Thus, the two datasets have the same mean but the second dataset has a larger sample size so it has a smaller standard error.

Additional Resources

How to Calculate the Standard Error of the Mean in R
How to Calculate the Standard Error of the Mean in Excel
How to Calculate Standard Error of the Mean in Google Sheets

The standard error or stderr is used to output errors and error messages in Linux systems. It is especially used in the bash shell to redirect errors and separate the errors from informational messages. Python provides different methods in order to print specific messages into the stderr. The most popular and easy way is using the print() method and provides the stderr as the output.

Print Standard Output or stdout with print() Method

First, start with a standard example where we will print to the standard output. Actually, the print() method prints the given data into the standard output or stdout.

print("This is standard output")

Even the print() method redirects or prints to the standard output or stdout we can also explicitly specify the standard output or stdout with the file parameter of the print() method.

import sys

print("This is standard output",file=sys.stdout)

Print Standard Error or stderr with print() Method

The print() method can be used to standard error or stderr. The file parameter should be set with the sys.stderr which is provided via the sys module. In the following examples, we will print the given string value or string variable into the stderr.

import sys

#Print string value to stderr
print("This is standard error",file=sys.stderr)

#Print string variable to stderr
errmessage = "This is standard error"
print(errmessage ,file=sys.stderr)

#Print list variable to stderr
errmessage = ["Error","Number",123]
print(errmessage ,file=sys.stderr)

The biggest advantage of using the print() method to print into standard error or stderr the print() method can convert provided data into the string. The data can be an integer, list, tuple, etc.

Print Standard Error or stderr with sys.write() Method

Python also provides the sys.stderr.write() method which can be used to print into the standard error or stderr. The write() method is less flexible than print() method in order to print into stderr because the write() method does not converts provided data automatically into the string type. So the provided data should be string type if not it should be converted properly. Also, the write() does not add a new line at the end of the data automatically. If we need the end of the line should be added explicitly with the “n” characters.

import sys

#Print string value to stderr
sys.stderr.write("This is standard errorn")


#Print string variable to stderr
errmessage = "This is standard errorn"
sys.stderr.write(errmessage)

Create Special Print Function To Print Standard Error or stderr

If we will print messages and data into the stderr frequently and do not want to write related print() or write() method again and again with parameters we can create a special function which will use the print() or write() method in order to print into stderr. The special Error Printing Function named as print_err() but you can change it into whatever you want.

import sys

def print_err(err_message):
   print(err_message,file=sys.stderr)


#Print string value to stderr
print_err("This is standard error")


#Print string variable to stderr
errmessage = "This is standard error"
print_err(errmessage)


#Print list variable to stderr
errmessage = ["Error","Number",123]
print_err(errmessage)

Объекты стандартного ввода, вывода и ошибки.

Синтаксис:

import sys

sys.stdin
sys.stdout
sys.stderr

Описание:

  • sys.stdin — используется для всех интерактивных входных данных, включая вызовы input();
  • sys.stdout — используется для вывода оператором print() и выражений, которые возвращают значение, а также для подсказок в функции input();
  • sys.stderr — сообщения об ошибках и собственные запросы переводчика.

Эти потоки являются обычными текстовыми файлами, такими же, как и те, которые возвращаются функцией open().

Их параметры выбираются следующим образом

:

  • Кодировка символов зависит от платформы. Не-Windows платформы используют кодировку локали locale.getpreferredencoding().

  • В Windows UTF-8 используется для консольного устройства. Не символьные устройства, такие как дисковые файлы и каналы, используют кодировку языкового стандарта системы, то есть кодовую страницу ANSI. Не консольные символьные устройства, такие как NUL, т.е. где метод isatty() возвращает True, используют значение кодовых страниц ввода и вывода консоли при запуске соответственно для sys.stdin и sys.stdout/sys.stderr. По умолчанию используется системная кодировка локали, если процесс изначально не подключен к консоли.

Особое поведение консоли можно изменить, установив переменную окружения PYTHONLEGACYWINDOWSSTDIO перед запуском Python. В этом случае кодовые страницы консоли используются как для любого другого символьного устройства.

На всех платформах можно переопределить кодировку символов, установив переменную среды PYTHONIOENCODING перед запуском Python или используя новый параметр командной строки — X utf8 и переменную среды PYTHONUTF8. Однако для консоли Windows это применимо только в том случае, если также установлено PYTHONLEGACYWINDOWSSTDIO.

В интерактивном режиме потоки stdout и stderr буферизуются по строкам. В противном случае они буферизируются как обычные текстовые файлы. Вы можете переопределить это значение с помощью параметра командной строки -u.

Примечание. Для записи или чтения двоичных данных из/в стандартные потоки используйте базовый объект двоичного буфера. Например, чтобы записать байты в sys.stdout используйте sys.stdout.buffer.write(b'abc').

Однако, если вы пишете модуль или библиотеку и не контролируете, в каком контексте будет выполняться ее код, помните, что стандартные потоки могут быть заменены файловыми объектами, такими как io.StringIO, которые не поддерживают атрибут буфера.

Изменено в Python 3.9: не интерактивный sys.stderr теперь буферизуется по строкам, а не полностью.

sys.__stdin__,
sys.__stdout__,
sys.__stderr__
:

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

Его также можно использовать для восстановления реальных файлов в известные рабочие файловые объекты, если они были перезаписаны поврежденным объектом. Однако предпочтительный способ сделать это — явно сохранить предыдущий поток перед его заменой и восстановить сохраненный объект.

Примечание. При некоторых условиях sys.stdin, sys.stderr и sys.stdout, а также исходные значения sys.__stdin__, sys.__stdout__ и sys.__stderr__ могут быть None. Обычно это относится к приложениям с графическим интерфейсом Windows, которые не подключены к консоли, а приложения Python запускаются с pythonw.exe(1).

Примеры использования sys.stdout, sys.stderr:

  • Сохранение вывода stdout и/или stderr в файл;
  • Сохранение вывода stdout и/или stderr в переменную в Python;
  • Перенаправление вывода stdout и/или stderr при помощи contextlib.redirect_std*();
  • Печать в консоль с задержкой (как телетекст…).

Сохранение вывода stdout и/или stderr в файл.

Этот код ничего не выводит на консоль, но записывает «Hello World» в текстовый файл с именем file.txt.

stdout = sys.stdout

try:
    sys.stdout = open('file.txt', 'w')
    print('Hello World')
finally:
    # Закрываем file.txt
    sys.stdout.close()
    sys.stdout = stdout

Чтобы сделать такие вещи менее подверженными ошибкам, Python предоставляет sys.__stdin__, sys.__stdout__ и sys.__stderr__ которые всегда содержат исходные значения sys.stdin, sys.stdout и sys.stderr. Приведенный выше код можно было бы сделать проще, используя sys.__stdout__:

try:
    sys.stdout = open('file.txt', 'w')
    print('blah')
finally:
    # Закрываем file.txt
    sys.stdout.close()  
    sys.stdout = sys.__stdout__

Причина, по которой Python имеет как sys.stdout , так и sys.__stdout__ в основном заключается в удобстве, поэтому вам не нужно создавать переменную для копирования stdout = sys.stdout

Сохранение stdout и/или stderr в переменную в Python.

Чтобы сохранить stdout в переменную нужно подменить sys.stdout собственным объектом io.StringIO, сделав что-то вроде:

from io import StringIO
import sys
 
# сохраняем ссылку, чтобы потом 
# снова отобразить вывод в консоли.
tmp_stdout = sys.stdout
 
# В переменной `result` будет храниться все, 
# что отправляется на стандартный вывод
result = StringIO()
sys.stdout = result
 
# Здесь все, что отправляется на стандартный вывод, 
# будет сохранено в переменную `result`.
do_fancy_stuff()
 
# Снова перенаправляем вывод `sys.stdout` на консоль
 sys.stdout = tmp_stdout
 
# Получаем стандартный вывод как строку!
result_string = result.getvalue()
# далее что-нибудь делаем с переменной стандартного вывода
process_string(result_string)

Перенаправление вывода stdout и/или stderr при помощи contextlib.redirect_std*().

import contextlib, io

s = io.StringIO()
with contextlib.redirect_stdout(s):
    help(pow)

>>> s.getvalue()[:50]
# 'Help on built-in function pow in module builtins:n'

Чтобы отправить вывод функции help() в файл на диске, нужно перенаправить вывод в обычный файл:

with open('help.txt', 'w') as fp:
    with contextlib.redirect_stdout(fp):
        help(pow)

Чтобы отправить вывод help() в sys.stderr:

import contextlib, sys

with redirect_stdout(sys.stderr):
    help(pow)

Пример печати текста в консоль с задержкой.

Определим функцию печати в консоль с задержкой так, что бы ее можно было использовать вместо встроенной функции print().

import sys, time
def teleprint(*args, delay=0.05, str_join=' '):
    text = str_join.join(str(x) for x in args)
    n = len(text)
    for i, char in enumerate(text, 1):
        if i == n:
            char = f'{char}n'
        sys.stdout.write(char)
        sys.stdout.flush()
        time.sleep(delay) 

# Строка будет печататься с задержкой, как в телетексте...
>>> teleprint('Печать с задержкой!', 10, 12.5, 'Super!!!', delay=0.07)
# Печать с задержкой!, 10, 12.5, Super!!

Сноски

  1. Если вы не хотите, чтобы при запуске вашей программы открывалось окно терминала, используйте pythonw.exe, в противном случае используйте python.exe

Понравилась статья? Поделить с друзьями:
  • Std error handle
  • Std domain error
  • Stc profile false как исправить
  • Stb does not support the inserted smart card error 8
  • Stay out как изменить ник