3

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
Community
  • 1
  • 1
iridescent
  • 305
  • 4
  • 14
  • 1
    Hey I have a very similar question that I asked yesterday. Luckily someone answered it. I'm sorry no one has commented on yours. Anyways the answer is that stderr is used for user interaction. It's part of the POSIX standard. "Each time an interactive shell is ready to read a command, the value of this variable ($PS1) shall be subjected to parameter expansion and written to standard error." https://stackoverflow.com/questions/41789077/unexpected-redirect-result-with-21-and-command-prompt/41792113#41792113 I hope this helps! Sorry to see how late I am! – Arrow Jan 23 '17 at 05:08

0 Answers0