Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
326 views
in Technique[技术] by (71.8m points)

python - How to input a word in ncurses screen?

I was trying to use raw_input() function first, but find it in compatible with ncurses.
Then I tried window.getch() function, I can type and show characters on screen, but can't realize input. How can I input a word in ncurses and can use if statement to evaluate it?

For example, I wanna realize this in ncurses:

import ncurses
stdscr = curses.initscr()

# ???_input = "cool" # this is the missing input method I want to know
if ???_input == "cool":
    stdscr.addstr(1,1,"Super cool!")
stdscr.refresh()
stdscr.getch()
curses.endwin()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Function raw_input( ) doesn't works in curses mode, The getch() method returns an integer; it represents the ASCII code of the key pressed. The will not work if you wants to scan string from prompt. You can make use of getstr function:

window.getstr([y, x])

Read a string from the user, with primitive line editing capacity.

User Input

There’s also a method to retrieve an entire string, getstr()

curses.echo()            # Enable echoing of characters

# Get a 15-character string, with the cursor on the top line
s = stdscr.getstr(0,0, 15)

And I wrote raw_input function as below:

def my_raw_input(stdscr, r, c, prompt_string):
    curses.echo() 
    stdscr.addstr(r, c, prompt_string)
    stdscr.refresh()
    input = stdscr.getstr(r + 1, c, 20)
    return input  #       ^^^^  reading input at next line  

call it as choice = my_raw_input(stdscr, 5, 5, "cool or hot?")

Edit: Here is working example:

if __name__ == "__main__":
    stdscr = curses.initscr()
    stdscr.clear()
    choice = my_raw_input(stdscr, 2, 3, "cool or hot?").lower()
    if choice == "cool":
        stdscr.addstr(5,3,"Super cool!")
    elif choice == "hot":
        stdscr.addstr(5, 3," HOT!") 
    else:
        stdscr.addstr(5, 3," Invalid input") 
    stdscr.refresh()
    stdscr.getch()
    curses.endwin()

output:

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...