print() function with encoding= and errors= parameters?

Chris Angelico rosuav at gmail.com
Wed Aug 3 11:44:55 EDT 2016


On Thu, Aug 4, 2016 at 1:35 AM, Malcolm Greene <python at bdurham.com> wrote:
> My use case was diagnostic output being (temporarily) output to stdout
> via debug related print statements. The output is for debugging only and
> not meant for production. I was looking for a solution that would allow
> me to output to the console with as few changes to the original scripts
> as possible, eg. non-invasive except for the print statements
> themselves.

Don't forget that the print function can simply be shadowed. If you
have a lot of code that uses print(...) to output text, and you want
to quickly transform it so it uses ASCII + backslash-replace, you
could simply:

def print(msg):
    sys.stdout.write(msg.encode("ASCII",
errors="backslashreplace").decode("ASCII") + "\n")

or whatever other transformation you want. Your current situation may
be solved, but this is a great tool in your toolbox, and worth bearing
in mind.

ChrisA



More information about the Python-list mailing list