5

I would like to capture error messages which are generated from a python module A. A is written in C++ and SWIG, and so I cannot capture Python's sys.stderr.

>>> import A >>> A.func() # this prints an error message by C++ std::cerr. this is an error message from module A 

What I want to do are to suppress the error message and to change my script behavior according to the error type. But A.func() does not return error numbers.


Assuming that my use of contextlib below is correct, it did not help.

>>> import io >>> f = io.StringIO() >>> import contextlib >>> with contextlib.redirect_stderr(f): ... no_return = A.func() ERROR MESSAGE HERE >>> f.getvalue() >>> 
6
  • why not use a try statement ? Commented Sep 7, 2018 at 9:29
  • @gogaz That would still not catch output written to std::cerr or would it? Commented Sep 7, 2018 at 9:31
  • Does contextlib redirect_stdout work for you? In that case, this is a duplicate: stackoverflow.com/questions/6796492/… Commented Sep 7, 2018 at 9:37
  • It didn't work. I should have mentioned it. I will edit the original post. Commented Sep 7, 2018 at 9:45
  • 1
    You will need to mess with its low-level file descriptor to get at the real stderr. See the stuff about file descriptors in the os module docs, and check out this article about redirecting C-level stdout in Python. eli.thegreenplace.net/2015/… Commented Sep 7, 2018 at 10:07

1 Answer 1

2

Thank you @PM2Ring

https://eli.thegreenplace.net/2015/redirecting-all-kinds-of-stdout-in-python/#id1

With minor modifications: replacing all the stdout with stderr and supporting macOS as shown below, it worked perfectly as expected.

if sys.platform == 'darwin': c_stderr = ctypes.c_void_p.in_dll(libc, '__stderrp') else: c_stderr = ctypes.c_void_p.in_dll(libc, 'stderr') 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.