Lawrence Leung
Lawrence Leung

Reputation: 1

Python redirect C++ library stdout to tempfile while it is also redirected in shell

I am calling a C++ library in my Python code, and I want to redirect all the stdout of that library into a temp file for post processing. (I know it is a bad design decision.......)

I have read through multiple similar questions and find that this can be done by redirect at the file descriptor level using os.dup2() Redirect stdout and stderr of an external library in Python

redirect_file = tempfile.TemporaryFile(mode='w+b')
stdout_fd = sys.stdout.fileno()
sys.stdout.close()
os.dup2(redirect_file.fileno(), stdout_fd)
# call C++ library here, capture output in redirect_file

However, I find that it only works if the Python script is executed without shell redirection. With shell redirection, the C++ library output will not be captured by temp file, and so I cannot do my post processing.

$ python foo.py                         # this works
$ python foo.py > redirected_output     # C++ output will appear in the redirected_output directly

Due to other constraint my code must be executed with redirection in shell, so I need to solve it within Python.

Upvotes: 0

Views: 75

Answers (0)

Related Questions