Python stdout not clearing properly after invoking curses

I have a program that uses curses, and then returns to the main script for further processing. After he returns, my subsequent output to stdout will not appear until there are a large number (for example, thousands of bytes).

I reduced the problem to a very simple program that does not work reliably:

import curses
import time

curses.initscr()
curses.endwin()

print "Hello world!"
time.sleep(5)

If I comment on the two calls to curses, "Hello world!" prints before a delay. If I insert them, it prints after a delay (when the script exits).

+3
source share
4 answers

curses.endwin() " - "... , , "" ( curses Python).

, ,

import os

sys.stdout = os.fdopen(0, 'w', 0)

( import os ; sys.stdout endwin).

+3

( , ), , .

import curses
import time
import os
import sys


class CursesStdout(object):
    def __enter__(self):
        pass

    def __exit__(self, *args):
        sys.stdout = sys.__stdout__ = os.fdopen(sys.__stdout__.fileno(), 'w', 0)

with CursesStdout():
    curses.initscr()
    curses.endwin()


print "Hello world!"
time.sleep(2)

sys.__stdout__ , , curses/__init__.py, , initscr C, reset .

+1

:

import sys
import curses

correct_stdout = sys.stdout    # remember correct

curses.initscr()
curses.endwin()

sys.stdout = correct_stdout    # restore correct
+1

, tis /. Windows ( http://www.lfd.uci.edu/~gohlke/pythonlibs/) , , Linux . , : sys.stdout.flush() like:

print "Hello world!"
sys.stdout.flush()
time.sleep(5)

( - " " )

0

Source: https://habr.com/ru/post/1764628/


All Articles