How to redirect raw_input to stderr, not stdout

I want to redirect stdout to a file. But this will affect raw_input . I need to redirect raw_input output to stderr instead of stdout . How can i do this

+6
source share
3 answers

Redirect stdout to stderr temporarily, then restore.

 import sys old_raw_input = raw_input def raw_input(*args): old_stdout = sys.stdout try: sys.stdout = sys.stderr return old_raw_input(*args) finally: sys.stdout = old_stdout 
+2
source

The only problem with raw_input is that it prints a prompt to stdout. Instead of trying to intercept this, why not just print the request yourself and call raw_input without a prompt that prints nothing to stdout?

 def my_input(prompt=None): if prompt: sys.stderr.write(str(prompt)) return raw_input() 

And if you want to replace raw_input with this:

 import __builtin__ def raw_input(prompt=None): if prompt: sys.stderr.write(str(prompt)) return __builtin__.raw_input() 

(For more information, see the docs __builtin__ , the module that raw_input and others are built-in, in functions . Usually you don't need to import it, but there is nothing in the docs that ensures it's better to be safe ...)

In Python 3.2+, the module is called builtins instead of __builtin__ . (Of course, 3.x does not have raw_input , in the first place, it was renamed to input , but the same idea could be used there.)

+13
source

Use getpass

 import getpass value=getpass.getpass("Enter Name: ") print(value) 

This will print the contents of value to stdout and Enter Name: to stderr.

Tested and works with python 2.7 and 3.6.

0
source

All Articles