Based on the answer marked as the solution in this thread, I have changed all stdout
to stderr
and the file descriptors
to 2
instead of 1
to use it for redirecting stderr
instead. It is successfully working, except when I use input()
after calling the redirecting function.
def redirect_stderr():
print("Redirecting stderr")
sys.stderr.flush() # <--- important when redirecting to files
# Duplicate stderr (file descriptor 2)
# to a different file descriptor number
newstderr = os.dup(2)
# os.devnull is used just to discard what is being printed
devnull = os.open(os.devnull, os.O_WRONLY)
# Duplicate the file descriptor for os.devnull
# and overwrite the value for stderr (file descriptor 2)
os.dup2(devnull, 2)
# Close devnull after duplication (no longer needed)
os.close(devnull)
# Use the original stderr to still be able
# to print to stderr within python
sys.stderr = os.fdopen(newstderr, 'w')
Example:
redirect_stderr()
a = input('hello: ')
print('please print me')
The text prompt within the input()
function would not appear in command prompt.
However, the text prompt appears when I run it using Pycharm's interactive console.
Any help is greatly appreciated.
Update
This method of redirecting stderr
does show the text prompt for input()
:
# Store the reference, in case you want to show things again in standard error
old_stderr = sys.stderr
# This variable will store everything that is sent to the standard error
result = io.StringIO()
sys.stderr = result
a = input('hello: ')
# re-enable printing to stderr
sys.stderr = old_stderr