timofurrer / colorful

Terminal string styling done right, in Python :snake: :tada:
MIT License
525 stars 23 forks source link

colorful dicts in system service app #43

Closed guydepauw closed 4 years ago

guydepauw commented 4 years ago

I have a flask app that I run as a system service. I love using colorful for debugging purposes, but when I deploy the app as a system service, using colorful to print a dictionary is producing this error

TypeError: __str__ returned non-string (type dict)

Are there any environment variables I can use to prevent this?

timofurrer commented 4 years ago

Can you please share a little bit more about how you use it? Like the code involved here?

guydepauw commented 4 years ago

Sure! Here is a summarized version of the flask app

from flask import Flask, request, jsonify, render_template
import colorful as cf

app = Flask(__name__)

@app.route('/proximity', methods=['GET', 'POST'])
def proximity():
    p = {'$geometry': {'type': 'Point'}}
    print(cf.cyan("hello world"))
    print(cf.cyan(p))
    return jsonify(p)

if __name__ == "__main__":
    app.run(port=7800, debug=True)

Everything works fine if I run the app from the command line, but as a system service, this works

print(cf.cyan("hello world"))

but this

print(cf.cyan(p))

renders the error message

TypeError: __str__ returned non-string (type dict)

timofurrer commented 4 years ago

Converting p to str explicitly helps, right?

guydepauw commented 4 years ago

It does! And just printing the dictionary works as well. But cf-printing the dictionary throws the error.

guydepauw commented 4 years ago

It seems to be a redirection thing, not having to do with anything system-service related in particular.

Consider test.py

import colorful as cf
a = {'b':1}

print(a)
print(cf.green(a))

then

python3 test.py > log

will fail with the aforementioned error message.

This is fixed by using your environment variable

COLORFUL_FORCE_TRUE_COLORS=1 python3 tt.py

So I'm all good now!