Setting the correct encoding when piping stdout in Python

Your code works when run in an script because Python encodes the output to whatever encoding your terminal application is using. If you are piping you must encode it yourself. A rule of thumb is: Always use Unicode internally. Decode what you receive, and encode what you send. # -*- coding: utf-8 -*- print u”åäö”.encode(‘utf-8’) … Read more

Redirect stdout to a file in Python?

If you want to do the redirection within the Python script, setting sys.stdout to a file object does the trick: # for python3 import sys with open(‘file’, ‘w’) as sys.stdout: print(‘test’) A far more common method is to use shell redirection when executing (same on Windows and Linux): $ python3 foo.py > file

Disable output buffering

From Magnus Lycka answer on a mailing list: You can skip buffering for a whole python process using python -u (or #!/usr/bin/env python -u etc.) or by setting the environment variable PYTHONUNBUFFERED. You could also replace sys.stdout with some other stream like wrapper which does a flush after every call. class Unbuffered(object): def __init__(self, stream): … Read more

How can I pipe stderr, and not stdout?

First redirect stderr to stdout — the pipe; then redirect stdout to /dev/null (without changing where stderr is going): command 2>&1 >/dev/null | grep ‘something’ For the details of I/O redirection in all its variety, see the chapter on Redirections in the Bash reference manual. Note that the sequence of I/O redirections is interpreted left-to-right, … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)