1

I make a custom command in Django where make some output to stdout. How I can intercept stdout make some changes(for example add prefix) and write to stderr? This is test task so do not pay attention on illogicality of question.

Vadim Zabolotniy
  • 307
  • 4
  • 15

2 Answers2

5

You can use StringIO like this:

from io import StringIO
import sys

old_stdout = sys.stdout
sys.stdout = mystdout = StringIO()

print("test")

sys.stdout = old_stdout

s = mystdout.getvalue()
s = "prefix" + s

sys.stderr.write(s)

The code is capturing stdout into the buffer, then reads the buffer, adds prefix and writes to stderr.

Also see:

Zach Thompson
  • 247
  • 2
  • 7
alecxe
  • 441,113
  • 110
  • 1,021
  • 1,148
0

You can use sys.stdout and sys.stderr:

from sys import stdout, stderr
output_text = "Some text"
stdout.write('stdout: ' + output_text + '\n')
stderr.write('stderr: ' + output_text + '\n')

Demo:

monty@xonix:~/py$ python so.py &> foo.txt
monty@xonix:~/py$ cat foo.txt
stderr: Some text
stdout: Some text
Ashwini Chaudhary
  • 232,417
  • 55
  • 437
  • 487