def customwarn(message, category, filename, lineno, file=None, line=None):
    sys.stdout.write(warnings.formatwarning(message, category, filename,
        lineno))
warnings.showwarning = customwarn
warnings.warn('test warning')
How to redirect python warnings to a custom stream?