Python sys stdout flush

Использование метода sys.stdout.flush ()

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

Вот некоторая хорошая информация о (un) буферизованном вводе-выводе и почему это полезно:
http://en.wikipedia.org/wiki/Data_buffer
Буферизованный и небуферизованный IO

@Ciastopiekarz Как вы думаете? Если я возьму скрипт Python Эндрю Кларка и заменим строку печати sys.stdout.write(«%d» % i) , то мне придется раскомментировать вызов sys.stdout.flush() чтобы получить буфер для отображения в виде скрипт выполняется.

Рассмотрим следующий простой скрипт на Python:

import time import sys for i in range(5): print(i), #sys.stdout.flush() time.sleep(1) 

Это предназначено для печати одного числа каждую секунду в течение пяти секунд, но если вы запустите его как есть (в зависимости от используемой по умолчанию буферизации системы), вы можете не увидеть никаких выходных данных до завершения сценария, а затем все сразу увидите 0 1 2 3 4 выводится на экран.

Это связано с тем, что вывод буферизуется, и если вы не sys.stdout после каждого print вы не увидите результат сразу. Удалите комментарий из sys.stdout.flush() чтобы увидеть разницу.

Читайте также:  Java не открывает сертификат

В Python 3.x ‘print i’ следует заменить на print (i, end = »), потому что print () в Python 3 имеет префикс по умолчанию end = ‘\ n’, который заставляет консоль сбрасываться.

Я просто запутался, когда убираю запятую, она работает нормально, как и ожидалось. Есть ли буферная логика для новых строк ??

В соответствии с моим пониманием, когда мы выполняем инструкции печати, вывод будет записан в буфер. И мы увидим вывод на экране, когда буфер очистится (очищается). По умолчанию буфер будет сброшен, когда программа выйдет. НО МЫ МОЖЕМ ТАКЖЕ ПОЛУЧИТЬ БУФЕР В СООТВЕТСТВИИ С помощью инструкции sys.stdout.flush() в программе. В приведенном ниже буфере кода будет сброшен, когда значение я достигнет 5.

Вы можете понять, выполнив приведенный ниже код.

chiru @онлайн: ~ $cat flush.py

import time import sys for i in range(10): print i if i == 5: print "Flushing buffer" sys.stdout.flush() time.sleep(1) for i in range(10): print i, if i == 5: print "Flushing buffer" sys.stdout.flush() 

chiru @онлайн: ~ $python flush.py

0 1 2 3 4 5 Flushing buffer 6 7 8 9 0 1 2 3 4 5 Flushing buffer 6 7 8 9 

Источник

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

Источник

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