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

How to redirect and append both standard output and standard error to a file with Bash

cmd >>file.txt 2>&1 Bash executes the redirects from left to right as follows: >>file.txt: Open file.txt in append mode and redirect stdout there. 2>&1: Redirect stderr to “where stdout is currently going”. In this case, that is a file opened in append mode. In other words, the &1 reuses the file descriptor which stdout currently … 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: import sys sys.stdout = open(‘file’, ‘w’) print(‘test’) sys.stdout.close() A far more common method is to use shell redirection when executing (same on Windows and Linux): $ python 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): self.stream … Read more