pythoninput

Prevent Python from showing entered input


In Python when I change the value of a variable through raw_input in the terminal it would write a new line stating its new value. I wanted to know if there is a way to avoid that because straight after user's input there is a print function which uses the value received before. In the end the user will get both values: original and modified while for the purpose of my program he only has to see the modified.

I use IDLE to write my scripts and then execute them in terminal.

Update

A simple example would be the following. The input is string "Hello" and the output should be "Me: Hello". There should be no "Hello" before the final result.

a = raw_input()
print ("Me: " + a)

And the output should be just

Me: Hello

rather than

Hello
Me: Hello

Solution

  • if you want user to see the input, just mute sys.stdout (it's a bit hack tho):

    >>> from StringIO import StringIO
    >>> import sys
    >>> orig_out = sys.stdout
    >>> print 'give me input: ',
    give me input: 
    >>> sys.stdout = StringIO()
    >>> a = raw_input('')
    string I type
    >>> sys.stdout = orig_out
    >>> a
    >>> 'string I type'
    

    ...and if you put this into a function then it's exactly what you want!

    a.py

    ....
    
    def foo():
        orig_out = sys.stdout
        print 'give me input: ',
        sys.stdout = StringIO()
        a = raw_input()
        sys.stdout = orig_out
    
    if __name__ == '__main__':
        foo()
    

    running:

    yed@rublan $ ~ python a.py
    
    give me input: something I type!!!!!
    
    yed@rublan $ ~