Bhishan Poudel Bhishan Poudel - 3 months ago 6x
Python Question

Python: stdout to both console and textfile including errors

I would like to print the output of python to both console and a textfile including errors, if any.

So far my attempts are these:

Using console:

# note that it has missing ) sign

# in the terminal:
chmod a+x; ./ 2>&1 | tee output.txt
# does not print to oputut.txt if has syntax errors

Print to file (python3):

with open('out.txt', 'a') as f:
print('hello world', file=f)
# this does not print to console, only to the file

Defining a class called "Tee"

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author : Bhishan Poudel
# Date : Jul 12, 2016

# Imports
import sys
import subprocess

class Tee(object):
def __init__(self, *files):
self.files = files
def write(self, obj):
for f in self.files:
def flush(self) :
for f in self.files:

f = open('out.txt', 'w')
original = sys.stdout
sys.stdout = Tee(sys.stdout, f)
print('This works good, prints all the output to both console and to a file')
print("This does not print output to file in case of syntax errors")
print("This does not print output of")

Suppose I have an executable (from C program that prints hello)'./hello')
# How to print output of this executable to both console and outputfile?

Note: Code to produce executable hello

// gcc -o hello hello.c

int main() {
return 0; }

Related links:

How to redirect 'print' output to a file using python?

Output on the console and file using python


If you are using bash (minimum version 4), you can run: ./mystdout |& tee output.txt. Otherwise your suggestion ./mystdout 2>&1 | tee output.txt should also work.