stdin: processing characters

Kevin Simmons kps at sent.com
Thu Apr 27 19:23:32 EDT 2006


I have seen this question asked a few times but have not seen a
clear answer...

I have a python script that prompts the user for input from stdin via a
menu. I want to process that input when the user types in two characters
and not have to have the user press <CR>. As a comparison, in the bash
shell one can use (read -n 2 -p "-->" CHOICE; case $CHOICE in...). Works
great and is very
straightforward. I have searched the python library and have not found
an answer to this simply task. raw_input(n) won't do it. I have looked
at the curses stuff but that is a bit overkill for what I need. I have
tried a while statement reading in characters from sys.stdin but no luck
there either. I am looking for an efficient way to do this simple task.

Here is the bash code I want to do in python. I am only looking for help
with the read of stdin portions, not the case statement:

while [ "$1" == "" ]; do
    (echo "       ---------")
    (echo "       Functions")
    (echo "       ---------")
    (echo " option")
    (echo " ------ ---- Scanning ----------")
    (echo "   ss   Scan the System,    Run the scan tool.")
    (echo "   rs   Result of Scan,     Show the result of the last
    scan.")
    
    read -e -n 2 -p "-->" CHOICE
    case "$CHOICE" in
        ## scanning
        "ss" | "SS" )
        (echo "Scanning the system may take a very long time. Do you
        wish to proceed?")
        read -e -n 1 -p "[y/n]-->" INPUT
        if [ "$INPUT" == "y" ]; then
            sh scan -s
            cd - &>/dev/null
        else
            (echo)
            (echo "Scan aborted.")
        fi
        ;;   
    ... rest of case statement
    esac
done
-- 
  Kevin Simmons
  kps at sent.com




More information about the Python-list mailing list