Python Print Statement and Python Sys Stdout

Python Print Statement

In Python, a print statement is just a programmer-friendly tool. Interface to the standard output stream. From a technical point of view, this instruction converts objects to text view and either sends the result to standard output or passes to another file-like object. The python print statement is tightly coupled with the concept of files and streams in Python.

Since the standard output stream in Python is available as an object stdout from the built-in sys module (that is, sys.stdout), it is quite possible to simulate modify the behavior of the python print statement using the file write methods, although using print looks simpler.

The output operation is one of the differences between Python 3.0 and 2.6 were the most visible. In fact, the differences in the implementation of these operations are one of the main reasons for the impossibility performance of programs written for version 2.X under control version 3.X without changes to the program code. In particular, from the version the interpreter depends on how the print operation is formatted:

  • In Python 3.X, the print statement has become a built-in function that takes named arguments that define special functions. output presses.
  • In Python 2.X, print is a statement that has its own characteristic syntax.

we will look at the features of the print implementation in each of them separately. If you are lucky enough to work with programs written for one version Python, you can only read the section that is appropriate for your case. However, your situation may change, so it won’t be superfluous for you to get acquainted with both versions.

the print function in Python 3.0

Strictly speaking, print is not a kind of statement in version 3.0, this is just one of the expression instructions that we have seen in the previous section.

Usually, the call to the built-in print function is formatted as a separate line, because it does not return any value (more precisely, it returns a None object), which would be worth taking care of. Since in version 3.0 print is a regular function, not some kind of a special form, but the standard syntax for calling functions. Due to this special modes of operation are defined using named arguments. This form is not only more versatile but also provides better I have support for future extensions.

By comparison, the python print statement in version Python 2.6 has specialized syntax supporting features such as suppressing line termination and redirecting output to a file. In addition, the instruction print in 2.6 does not allow you to define delimiter strings at all; in 2.6 you are much more likely to have to construct strings in advance than in 3.0.



Python print statement Calling format:

The syntax for calling the print function in version 3.0 is as follows:

The items in square brackets here are optional and can be omitted, and the values ​​following the = sign determine the values ​​by default. Simply put, this built-in function outputs to file stream one or more objects in a text representation, separated by the string sep and ends the output with the end.

The sep, end, and file parameters, if required, should not be passed in the form of positional, and in the form of named arguments, that is, using by using the special name = value syntax.  Named arguments can be specified in any order in the call functions, but after the objects intended for output, and define the parameters output dimensions:

  • sep is the string to be inserted between objects in the output. The default is one space. To suppress the output of the delimiter string, pass an empty string in this argument.
  • the end is a string added to the end of the displayed text. Contains the end-of-line character \ n by default. If you pass an empty string in this argument, the next call to the print function will start printing text from the position where the current line ended.
  • file a file object, standard stream, or another object similar to the file where the text will be output. The default is the object ys.stdout standard output stream. This argument can be passed an object that supports the write (string) file method; if passes The actual file object must already be open for writing.

The textual representation of any object that is passed for output, the print function gets it using the str built-in function. As we already know, this function returns a human-readable string representation of any object.1 When called with no arguments, the print function will simply print out the character end of the line to standard output, which looks like the output is empty strings.

The print function in action:

Using the print function in version 3.0 is much easier than it could be I would assume after getting acquainted with some of its features. To illustrate, let’s take a few short examples. The following shows the order in which objects of various types are output to the default standard output stream, with a default separator line and a line terminator appended (these output parameter values ​​were default values ​​because they are used overwhelmingly in most cases):

In this example, there is no need to convert objects. to strings, as required by the methods for writing to files. The default function print prints a space character between objects. To suppress whitespace, simply pass an empty string in the sep named argument or specify another string separator:


In addition, the print function adds an end character at the end of the output line. strings. The output of this character can be suppressed by passing an empty string to the named argument end. Similarly, you can pass a different one in this argument. line separator (including the \ n character to manually provide translation lines):

The simultaneous use of named arguments defining separators between objects in a line and between lines can be specified in any order, but only after the objects that you want to display:

The following demonstrates how to use the named argument file. It can be used to redirect the output of text to a file open for writing, or to another object compatible with the output operation (in fact, this is a kind of stream redirection, which will be discussed below in this section):

Finally, keep in mind that the ability to identify a divider line and the line divider provided by print is just handy. If you need to get more complicated formatting doesn’t have to take advantage of this opportunity. In the world, hundred of these can be designed in advance or resort to help formatting tools, inside call the print function, and bring out the line that’s just Print call:

As we will see in the next section, almost everything that has been said about the print function in Python 3.0, the same applies to the python print statement in version 2.6, especially when you consider that the function was intended as further development and improvement of support for withdrawal operations in 2.6.


The print function in Python 2.6:

As mentioned above, the output operation in Python 2.6 is implemented as instructions with a unique and very specific syntax, not in the form built-in function. In practice, is printing? organized in 2.6 is a variation on the same theme – except for the delimiter lines (which are kept in version 3.0 and are not supported in version 2.6), for all other print functions in version 3.0 have direct analogs in the print structures in version 2.6.

Statement forms:

Table 1 lists the forms of the python print statement in Python 2.6 and the equivalent of their print calls in Python 3.0. Note that the comma in the python print statement is essential – it separates objects that are required to be printed and the trailing comma suppresses the output of the end line, which is usually displayed at the end of a line of text (do not confuse with the syntax of tuples!). The syntax >> is commonly used as a bitwise right shift operator, however, it can be used in print statements to define an output stream other than sys.stdout, which is the default.

Table 1: List of python print statement forms

Print statement in Python 2.6 Equivalent in Python 3.0 Interpretation
print x, y

 

print(x, y)

 

Outputting objects to sys.stdout; adds a space between objects and end symbol strings
print x, y,

 

print(x, y, end=’’)

 

The same, only for this times the end-of-line character is not added
print >> afile, x, y

 

print(x, y, file=afile)

 

The text is passed to the method myfile.write, not sys.stdout.write

The python print statement in action:

Although the syntax for the print statement in Python 2.6 is different from the syntax for the print function in Python 3.0, it is just as easy to use. Let’s take a look at some simple examples. Default statement print in  python 2.6 adds a space between items separated by commas and a line break at the end of the current line of output:

This formatting is just the default that you can use or not. To suppress the output of the end-of-line character (and later continue outputting text to the current line), the python print statement should be terminated with a comma character, as shown in the second line of table 1 (below the there are two statements on one line, separated by semicolons):

To suppress whitespace between items, output not in this way, instead, you need to independently assemble the string with by the power of the concatenation and formatting operation, and print this line:

As you can see from the examples, except for the special syntax for defining personal output modes, the python 2.6 print statement is almost as simple in use, just like the print function in 3.0. The next section describes how to redirect output to a file using the print statement in python 2.6.



Redirecting an Output Stream in Python Print Statement:

In both Python 3.0 and 2.6, the output text is sent to standard output by default. However, quite often it becomes necessary to output the text to some other place, for example, to a file, so that save the results for later use or for testing purposes. Such output redirection can be organized at the level system command shell, outside of the interpreter, however, governance within a script is no more complicated.

Hello world Python program:

Let’s start with the familiar (and common) test of the programming language with the “hello world” program. To display the message “hello world” in a program on in Python, just print the line:

Since the results of expressions in the interactive shell are displayed automatically mathematically, you may not even use the python print statement just type the expression that you want to output, and the result of its evaluation immediately will be outputted:

This fragment can hardly be called an example of a programming skill, so no less, it clearly demonstrates the features of the behavior of the output operation. In reality, the python print statement is just an ergonomic feature of the Python language – it provides a simple interface to the sys.stdout object, adding a minor amount of formatting. In fact, if you like going the harder way, you can program the output so in this way:

This snippet explicitly calls the write method of the sys.stdout attribute, preset by the Python interpreter when opening a file associated with an output stream. The python print statement hides most of these details, providing a simple tool for solving simple tasks withdrawal.

Redirecting the output stream manually:

So why did I show a more complex way of output? As it turns out, the object sys.stdout provides output functionality equivalent to the basic Python methodology. Generally speaking, the python print statement and the object sys.stdout are related as following statement:

which manually converts the object to a string with function str, appends the end-of-line character using the + operator, and calls The write method of the output stream. How would you accomplish the same task? (By this with an example I would like to emphasize the friendly nature of the print statement…)

Obviously, the longer form itself is less convenient to use. However, it is good to know that it is the exact equivalent of the instruction print because it is possible to reassign sys.stdout to something other than the standard output stream. In other words, this equivalent valence provides the ability to force the print statement to output text to another location. For example:

Here we have manually redirected the sys.stdout object to a file opened manually in add mode (as we add new content). After this, all print statements in the program will print text to the end of the file log.txt instead of stdout. Print statements successfully must call the sys.stdout object’s write method no matter where it is referring to. Since there is only one sys module in each process, redirecting sys.stdout in this way will affect all the print structure in the program.

In fact, as will be discussed in the next sidebar describing the python print statement and the stdout object, it is possible to redirect sys.stdout to an object that isn’t even a file, provided it supports the expected interface: a write method that takes a string argument. This object can be a class capable of handling and transferring edit the displayed text in any way.

This technique of redirecting the output stream is primarily useful in programs that were originally designed to use the print statement. If you know that all output should be sent to a file, you can always organize the call of methods for writing to a file. When redirecting an output stream in instruction-based programs print, setting up the sys.stdout object provides a convenient alternative to change the behavior of all print statements or use redirection system command shell tools.


Automatic stream redirection:

Accepting redirection of text output by assigning a file to an object sys.stdout is very often used in practice. However, in the program code the previous section has one potential problem – missing a direct way to restore the original output stream, if suddenly, after outputting data to a file, you need to return back to the output on the screen. But since sys.stdout is a regular object, you can always save it and restore it later if necessary:

The need for such redirection arises surprisingly often, and manual Retention and restoration of the original output flow is a procedure for precisely complex, which led to an extension for the print statement, which makes such a redirection unnecessary. In version 3.0, the name file argument allows you to redirect to the file the only print call without resorting to reinstalling the sys.stdout value. Since this redirection is temporary, the usual print calls continue to display the text in the original output stream. In version 2.6, the same effect can be achieved by pointing out at the beginning print statement >> characters and after them is a file object (or another compatible object). For example, the next snippet displays text in the log file. Txt:


These redirection methods are useful when you need to organize output to both a file and standard output in the same program. However, if you are going to use these forms of output, you will need to create a file object (or an object that has a write method, just like an object file) and pass the instructions to this object, not a string with the file name:

These extended forms of the python print statement are often used to print error messages to standard error, sys.stderr. You can either use its write method and format the outputted lines manually or use the redirection syntax:

Now that you know all about output redirection, the equivalence of the print function and the write method of files should seem obvious to you. The following example demonstrates the output of text in both ways in version 3.0, then redirecting the output to an external file is demonstrated and the contents of the text files are checked:

As you can see, it is better to use print to display text, unless you really enjoy keyboard input. This is an example demonstrating the equivalence of using the print operation and the write method of files, an example of imitating the print function for Python 2.6.



Related Article:

Python loops For loops, Nested loops, While Loop

Python Regular Expressions or regex Matching, Searching, Replacing

Recommended For You

About the Author: Fawad

My name is Shahzada Fawad and I am a Programmer. Currently, I am running my own YouTube channel "Expertstech", and managing this Website. My Hobbies are * Watching Movies * Music * Photography * Travelling * gaming and so on...

Leave a Reply

%d bloggers like this: