Search code examples
pythonnewlinecarriage-returnraw-input

How to print over raw_input's line in Python?


Usually, when raw_input asks you to type something in and press Return, feedback is printed on a new line. How can I print over the prompt's line? Could a CR work in this case?

Demo:

prompt = "Question: "
answer = raw_input(prompt)
print answer
print("Correct!")

Simulated output after typing an answer and pressing Return:

>> Question: my answer
>> Correct!

Desired output:

>> Correct!

Solution

  • Use blessings:

    from blessings import Terminal
    term = Terminal()
    
    raw_input("Question: ")
    print(term.move_up() + "Correct!" + term.clear_eol())
    

    Seriously, that's it.

    Here's something fancier:

    input(term.red("Question: ") + term.bold)
    print(term.normal + term.move_up + term.green("Correct!") + term.clear_eol)
    

    This shows that often calling term.thing is optional because they act similarly to properties. This means you can do awesome stuff like

    from blessings import Terminal
    term = Terminal()
    
    question = "{t.red}{}{t.normal}{t.bold}".format
    answer = "{t.normal}{t.move_up}{t.green}{}{t.normal}{t.clear_eol}".format
    
    input(question("Question: ", t=term))
    print(answer("Correct!", t=term))