@@ -405,10 +405,13 @@ def getText(value, encoding=None):
405405
406406def stdoutEncode (value ):
407407 """
408- Returns binary representation of a given Unicode value safe for writing to stdout
408+ Returns textual representation of a given value safe for writing to stdout
409+ >>> stdoutEncode(b"foobar")
410+ 'foobar'
409411 """
410412
411- value = value or ""
413+ if value is None :
414+ value = ""
412415
413416 if IS_WIN and IS_TTY and kb .get ("codePage" , - 1 ) is None :
414417 output = shellExec ("chcp" )
@@ -418,36 +421,32 @@ def stdoutEncode(value):
418421 try :
419422 candidate = "cp%s" % match .group (1 )
420423 codecs .lookup (candidate )
421- except LookupError :
422- pass
423- else :
424424 kb .codePage = candidate
425+ except (LookupError , TypeError ):
426+ pass
425427
426428 kb .codePage = kb .codePage or ""
427429
428- if isinstance (value , six .text_type ):
429- encoding = kb .get ("codePage" ) or getattr (sys .stdout , "encoding" , None ) or UNICODE_ENCODING
430+ encoding = kb .get ("codePage" ) or getattr (sys .stdout , "encoding" , None ) or UNICODE_ENCODING
430431
431- while True :
432- try :
433- retVal = value .encode (encoding )
434- break
435- except UnicodeEncodeError as ex :
436- value = value [:ex .start ] + "?" * (ex .end - ex .start ) + value [ex .end :]
437-
438- warnMsg = "cannot properly display (some) Unicode characters "
439- warnMsg += "inside your terminal ('%s') environment. All " % encoding
440- warnMsg += "unhandled occurrences will result in "
441- warnMsg += "replacement with '?' character. Please, find "
442- warnMsg += "proper character representation inside "
443- warnMsg += "corresponding output files"
444- singleTimeWarnMessage (warnMsg )
445-
446- if six .PY3 :
447- retVal = getUnicode (retVal , encoding )
432+ if six .PY3 :
433+ if isinstance (value , (bytes , bytearray )):
434+ value = getUnicode (value , encoding )
435+ elif not isinstance (value , str ):
436+ value = str (value )
448437
438+ try :
439+ retVal = value .encode (encoding , errors = "replace" ).decode (encoding , errors = "replace" )
440+ except (LookupError , TypeError ):
441+ retVal = value .encode ("ascii" , errors = "replace" ).decode ("ascii" , errors = "replace" )
449442 else :
450- retVal = value
443+ if isinstance (value , six .text_type ):
444+ try :
445+ retVal = value .encode (encoding , errors = "replace" )
446+ except (LookupError , TypeError ):
447+ retVal = value .encode ("ascii" , errors = "replace" )
448+ else :
449+ retVal = value
451450
452451 return retVal
453452
0 commit comments