2

I keep running into errors with unicode while printing things from wikipedia out in my console. I found a solution (that doesnt make my console crash when trying to use weird characters like Ł) and the solution was putting this at the top of my main file:

sys.stdout = codecs.getwriter('utf8')(sys.stdout.buffer)

the thing is now my console doesn't print anything. Only when I cancel my code from running midway through does it show me what it was printing. It used to update in realtime (before I put the above code snippet in) as it pulled info from wikipedia. Can anyone explain how to fix this or an alternative solution.

To clarify: The error I would receive WITHOUT the above snippet of code was:

UnicodeEncodeError: 'charmap' codec can't encode character '\u0141' in position 6: character maps to <undefined>

now with the code snippet it won't print anything in realtime but it DOES prevent that error. When the program finally finishes it will print everything out all at once-- but I want it to print as it is going(as it did before). I am using Python 3.6.5

Pookie
  • 1,239
  • 1
  • 14
  • 44

1 Answers1

1

sys.stdout is a buffered stream, that is, output is stored in the stream and not output until the buffer is flushed.

The print function will flush its output stream automatically, but if you are writing to the stream directly (for example, sys.stdout.write('foo')) you need to call its flush() explicitly to send output to the console.

If sys.stdout is not flushed while a program is executing, it will be flushed automatically when the programme is terminated, as described in the question.

snakecharmerb
  • 47,570
  • 11
  • 100
  • 153