How to redirect the raw_input to stderr and not stdout?

前端 未结 3 1809
余生分开走
余生分开走 2021-01-12 04:53

I want to redirect the stdout to a file. But This will affect the raw_input. I need to redirect the output of raw_input to stde

相关标签:
3条回答
  • 2021-01-12 05:28

    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
    
    0 讨论(0)
  • 2021-01-12 05:31

    The only problem with raw_input is that it prints the prompt to stdout. Instead of trying to intercept that, why not just print the prompt yourself, and call raw_input with no prompt, which 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 info, see the docs on __builtin__, the module that raw_input and other built-in functions are stored in. You usually don't have to import it, but there's nothing in the docs that guarantees that, so it's better to be safe…)

    In Python 3.2+, the module is named builtins instead of __builtin__. (Of course 3.x doesn't have raw_input in the first place, it's been renamed input, but the same idea could be used there.)

    0 讨论(0)
  • 2021-01-12 05:39

    Use getpass

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

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

    Tested and works with python 2.7 and 3.6.

    0 讨论(0)
提交回复
热议问题