Sys stdout python print

Python print() to File

Learn to use Python print() function to redirect the print output of a Python program or Python script to a file.

1. Print to File using file Argument

The print() function accepts 5 keyword arguments apart of the objects to print on the standard output (by default, the screen). One such keyword argument is file.

The default value of the file argument is sys.stdout which prints the output on the screen. We can specify any other output target which must be an object with write(string) method.

The given Python program opens the demo.txt in writing mode and write the test ‘Hello, Python !’ into the file.

sourceFile = open('demo.txt', 'w') print('Hello, Python!', file = sourceFile) sourceFile.close()

2. Redirecting Standard Output Stream to a File

Specifying the file parameter in all print() statements may not be desirable in some situations. We can temporarily redirect all the standard output streams to a file in this case.

Once all the required objects are written in the File, we can redirect the standard output back to the stdout .

import sys # Saving the reference of the standard output original_stdout = sys.stdout with open('demo.txt', 'w') as f: sys.stdout = f print('Hello, Python!') print('This message will be written to a file.') # Reset the standard output sys.stdout = original_stdout print('This message will be written to the screen.')

The program outputs to the file after setting the standard output to the file.

Hello, Python! This message will be written to a file.

The program again outputs to the console after resetting the standard putout target.

This message will be written to the screen.

3. Redirecting Script Output to File

Another way to redirect the output is directly from the command line while executing the Python script. We can use > character to output redirection.

The script output is in the file.

Источник

Python’s print and the flush parameter.

If you’ve been in touch with the Python community relatively recently, you’ve probably heard of rich . rich brings colors to the terminal. without much of a hassle.

These two lines show rich.print overriding Python’s built-in print function. One thing that caught my attention is rich.print ‘s docstring, especially this line:

I seldomly use this parameter. But I do remember one place where I’ve seen it — pyautogui ‘s mouse documentation where Al Sweigart gave this code example which shows the coordinates of your cursor:

 #! python3 import pyautogui, sys print('Press Ctrl-C to quit.') try: while True: x, y = pyautogui.position() positionStr = 'X: ' + str(x).rjust(4) + ' Y: ' + str(y).rjust(4) print(positionStr, end='') print('\b' * len(positionStr), end='', flush=True) except KeyboardInterrupt: print('\n') 

What does flush do?

  • flush=False (yes, the default) will wait for the line to complete before printing it.
  • flush=True will force our terminal to print it.
  • flush does not matter if end=\n .

Now this begs the question, why? If I have end=» , why do I have to explicitly set flush=True ?

Below is the first sentence from Python’s print documentation:

print(*objects, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False)
Print objects to the text stream file , separated by sep and followed by end .

To be honest, when I first wrote my Hello World program in Python, I didn’t go through the documentation to get awed by its implementation. Now that I’ve seen it, I can infer that the terminal output is a «text stream» which is sys.stdout by default.

stdout is used for the output of print() and expression statements and for the prompts of input() .

These streams are regular text files like those returned by the open() function.

When interactive, the stdout stream is line-buffered. Otherwise, it is block-buffered like regular text files. You can make both streams unbuffered by passing the -u command-line option or setting the PYTHONUNBUFFERED environment variable.

There’s apparently a deep rabbit-hole to dig into this. More experienced programmers will probably recognize PYTHONUNBUFFERED in their Dockerfiles. We also probably want to know what’s the difference between line-buffered and block-buffered. Personally, I was aware of sys.stdout.write existing.

But for now, we can be comfortable knowing that terminal output is pretty much like a regular text file being read from somewhere. Hence, it makes sense that print , by default, would prefer to complete a line first before giving an output.

But how does this affect flush ?

  • Setting PYTHONUNBUFFERED via command line. I use Windows so in PowerShell, it’s something like $env:PYTHONUNBUFFERED = «TRUE» . This overrides flush=False . It also overrides os.unsetenv .
  • The os module (i.e., os.environ[‘PYTHONUNBUFFERED’] = «TRUE» ) does NOT override flush=False .
  • Via python -u flag. The -u flag overrides flush=False regardless of PYTHONUNBUFFERED value.

Now what?

Let us go back to Al Sweigart’s mouse code. This line is really interesting:

print('\b' * len(positionStr), end='', flush=True) 

Spoiler alert: you may delete the flush=True keyword argument. The character \b is backspace and already enough to delete positionStr . It’s probably there only to show some parallelism between this and the Python 2 code right beneath it. Nevertheless, you may play with this line — change end , modify len(positionStr) , you may even change the loop.

But what would flush do here? Hopefully, this article has given you the first step in the right direction.

Источник

Python sys.stdout Method

Python sys.stdout Method

  1. Syntax of Python sys.stdout Method
  2. Example Codes: Use the sys.stdout Method in Python
  3. Example Codes: sys.stdout.write() vs print() Method
  4. Example Codes: Use the sys.stdout.write() Method to Display a List
  5. Example Codes: Use the sys.stdout.flush() Method in Python
  6. Example Codes: Use the sys.stdout.encoding() Method in Python
  7. Example Codes: Duplicate sys.stdout to a Log File

One of the methods in the sys module in Python is stdout , which uses its argument to show directly on the console window.

These kinds of output can be different, like a simple print statement, an expression, or an input prompt. The print() method, which has the same behavior, first converts to the sys.stdout() method and then shows the result on the console.

Syntax of Python sys.stdout Method

Parameters

No parameter is involved. We use sys.stdout for the output file object.

Return

This method doesn’t return any value but only shows output directly on the console.

Example Codes: Use the sys.stdout Method in Python

# import the sys module to use methods import sys  sys.stdout.write('This is my first line') sys.stdout.write('This is my second line') 
This is my first line This is my second line 

It will return the passed argument in the sys.stdout.write() method and display it on the screen.

Example Codes: sys.stdout.write() vs print() Method

import sys # print shows new line at the end print("First line ") print("Second line ") # displays output directly on console without space or newline sys.stdout.write('This is my first line ') sys.stdout.write('This is my second line ') # for inserting new line sys.stdout.write("\n") sys.stdout.write('In new line ') # writing string values to file.txt print('Hello', 'World', 2+3, file=open('file.txt', 'w')) 
First line Second line This is my first line This is my second line In new line # file.txt will be created with text "Hello World 5" as a string 

We use the sys.stdout.write() method to show the contents directly on the console, and the print() statement has a thin wrapper of the stdout() method that also formats the input. So, by default, it leaves a space between arguments and enters a new line.

After Python version 3.0, print() method not only takes stdout() method but also takes a file argument. To give a line space, we pass the «\n» to the stdout.write() method.

Example Codes: Use the sys.stdout.write() Method to Display a List

import sys  # sys.stdout assigned to "carry" variable carry = sys.stdout my_array = ['one', 'two', 'three']  # printing list items here for index in my_array:  carry.write(index) 
# prints a list on a single line without spaces onetwothree 

The output shows that the stdout.write() method gives no space or new line to the provided argument.

Example Codes: Use the sys.stdout.flush() Method in Python

import sys # import for the use of the sleep() method import time # wait for 5 seconds and suddenly shows all output for index in range(5):  print(index, end =' ')  time.sleep(1) print() # print one number per second till 5 seconds for index in range(5):  # end variable holds /n by default  print(index, end =' ')  sys.stdout.flush()  time.sleep(1) 
0 1 2 3 4 # no buffer 0 1 2 3 4 # use buffer 

The sys.stdout.flush() method flushes the buffer. It means that it will write things from buffer to console, even if it would wait before it does that.

Example Codes: Use the sys.stdout.encoding() Method in Python

# import sys module for stdout methods import sys # if the received value is not None, then the function prints repr(receivedValue) to sys.stdout def display(receivedValue):  if receivedValue is None:  return  mytext = repr(receivedValue)  # exception handling  try:  sys.stdout.write(mytext)  # handles two exceptions here  except UnicodeEncodeError:  bytes = mytext.encode(sys.stdout.encoding, 'backslashreplace')  if hasattr(sys.stdout, 'buffer'):  sys.stdout.buffer.write(bytes)  else:  mytext = bytes.decode(sys.stdout.encoding, 'strict')  sys.stdout.write(mytext)  sys.stdout.write("\n")  display("my name") 

The method sys.stdout.encoding() is used to change the encoding for the sys.stdout . In the method display() , we use it to evaluate an expression inserted in an interactive Python session.

There is an exception handler with two options: if the argument value is encodable, then encode with the backslashreplace error handler. Otherwise, if it is not encodable, it should encode with the sys.std.errors error handler.

Example Codes: Duplicate sys.stdout to a Log File

import sys # method for multiple log saving in txt file class multipleSave(object):  def __getattr__(self, attr, *arguments):  return self._wrap(attr, *arguments)  def __init__(self, myfiles):  self._myfiles = myfiles  def _wrap(self, attr, *arguments):  def g(*a, **kw):  for f in self._myfiles:  res = getattr(f, attr, *arguments)(*a, **kw)  return res  return g  sys.stdout = multipleSave([ sys.stdout, open('file.txt', 'w') ]) # all print statement works here print ('123') print (sys.stdout, 'this is second line') sys.stdout.write('this is third line\n') 
# file.txt will be created on the same directory with multiple logs in it. 123 __main__.multipleSave object at 0x00000226811A0048> this is second line this is third line 

To store output console results in a file, we can use the open() method to store it. We store all the console outputs in the same log file.

This way, we can store any output printed to the console and save it to the log file.

Related Article — Python Sys

Источник

Читайте также:  Check if type is list in python
Оцените статью