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.
Asked
Active
Viewed 1,295 times
2 Answers
6
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
- 272
- 2
- 7

alecxe
- 462,703
- 120
- 1,088
- 1,195
-1
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
- 244,495
- 58
- 464
- 504