2014-12-04 96 views
4

通常,當raw_input要求您鍵入內容並按回車鍵時,反饋將打印在新行上。我該如何在提示行上打印?在這種情況下,CR可以工作嗎?如何通過Python打印raw_input的行?

演示:

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

鍵入答案和按回車鍵後模擬輸出:

>> Question: my answer 
>> Correct! 

希望的輸出:

>> Correct! 
+2

真棒的東西,如果在UNIX上,你可以嘗試詛咒 - https://docs.python.org/2/howto/curses.html – 2014-12-04 21:13:28

+0

@BhargavRao我打算學[urwid]( http://urwid.org),但在那之前,我正在尋找一個簡單的解決方案。 – octosquidopus 2014-12-04 21:15:48

+0

有3個選項比2更簡單(我猜) – 2014-12-04 21:17:17

回答

3

使用blessings

from blessings import Terminal 
term = Terminal() 

raw_input("Question: ") 
print(term.move_up() + "Correct!" + term.clear_eol()) 

說真的,就是這樣。

這裏的東西票友:

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

這表明,經常打電話term.thing是可選的,因爲他們同樣採取行動的性質。這意味着你可以不喜歡

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)) 
4

這是使用curses的溶液(末它等待x鍵結束程序):

#!/usr/bin/python                

import time 
import sys 
import curses 

def questionloop(stdscr): 
    stdscr.addstr("Question: ") 
    curses.echo() 
    while (1): 
     answer = stdscr.getstr() 
     curses.flushinp() 
     stdscr.clear() 
     stdscr.addstr("This is correct!") 
     doit = stdscr.getch() 
     if doit == ord('x'): 
     stdscr.addstr("Exiting!\n") 
     break 

curses.wrapper(questionloop) 

這是使用urwid一個例子:

import urwid 

def exit_on_q(key): 
    if key in ('q', 'Q'): 
     raise urwid.ExitMainLoop() 

class QuestionBox(urwid.Filler): 
    def keypress(self, size, key): 
     if key != 'enter': 
      return super(QuestionBox, self).keypress(size, key) 
     self.original_widget = urwid.Text(
      u"%s\n" % 
      edit.edit_text) 

edit = urwid.Edit(u"Question: \n") 
fill = QuestionBox(edit) 
loop = urwid.MainLoop(fill, unhandled_input=exit_on_q) 
loop.run() 

另一個(可能是最簡潔的)解決方案,from Veedrac's answer,是使用blessings

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))