cbbcbail
cbbcbail

Reputation: 1771

Constantly looking for user input in Python

How would I write a Python program that would always be looking for user input. I think I would want to have a variable equal to the input and then something different would happen based on what that variable equaled. So if the variable were "w" then it would execute a certain command and keep doing that until it received another input like "d" Then something different would happen but it wouldn't stop until you hit enter.

Upvotes: 3

Views: 10671

Answers (5)

keramat
keramat

Reputation: 4543

if you want to get input repeatedly from user;

x=1
while x==1:
    inp = input('get me an input:')

and based on inp you can perform any condition.

Upvotes: 1

kenkeiras
kenkeiras

Reputation: 11

Maybe select.select is what you are looking for, it checks if there's data ready to be read in a file descriptor so you can only read where it avoiding the need to interrupt the processing (well, in the example it waits one second but replace that 1 with 0 and it'll work perfectly):

import select
import sys

def times(f): # f: file descriptor
    after = 0

    while True:
        changes = select.select([f], [], [], 1)

        if f in changes[0]:

            data = f.readline().strip()

            if data == "q":
                break

            else:
                print "After", after, "seconds you pressed", data

        after += 1

times(sys.stdin)

Upvotes: 1

Rik Poggi
Rik Poggi

Reputation: 29312

If you want to constantly look for an user input you'll need multithreading.

Example:

import threading
import queue

def console(q):
    while 1:
        cmd = input('> ')
        q.put(cmd)
        if cmd == 'quit':
            break

def action_foo():
    print('--> action foo')

def action_bar():
    print('--> action bar')

def invalid_input():
    print('---> Unknown command')

def main():
    cmd_actions = {'foo': action_foo, 'bar': action_bar}
    cmd_queue = queue.Queue()

    dj = threading.Thread(target=console, args=(cmd_queue,))
    dj.start()

    while 1:
        cmd = cmd_queue.get()
        if cmd == 'quit':
            break
        action = cmd_actions.get(cmd, invalid_input)
        action()

main()

As you'll see this, will get your messages a little mixed up, something like:

> foo
> --> action foo
bar
> --> action bar
cat
> --> Unknown command
quit

That's beacuse there are two threads writing to stdoutput at the same time. To sync them there's going to be need of lock:

import threading
import queue

def console(q, lock):
    while 1:
        input()   # Afther pressing Enter you'll be in "input mode"
        with lock:
            cmd = input('> ')

        q.put(cmd)
        if cmd == 'quit':
            break

def action_foo(lock):
    with lock:
        print('--> action foo')
    # other actions

def action_bar(lock):
    with lock:
        print('--> action bar')

def invalid_input(lock):
    with lock:
        print('--> Unknown command')

def main():
    cmd_actions = {'foo': action_foo, 'bar': action_bar}
    cmd_queue = queue.Queue()
    stdout_lock = threading.Lock()

    dj = threading.Thread(target=console, args=(cmd_queue, stdout_lock))
    dj.start()

    while 1:
        cmd = cmd_queue.get()
        if cmd == 'quit':
            break
        action = cmd_actions.get(cmd, invalid_input)
        action(stdout_lock)

main()

Ok, now it's better:

    # press Enter
> foo
--> action foo
    # press Enter
> bar
--> action bar
    # press Enter
> cat
--> Unknown command
    # press Enter
> quit

Notice that you'll need to press Enter before typing a command to enter in "input mode".

Upvotes: 6

CR0SS0V3R
CR0SS0V3R

Reputation: 336

You can also use definitions, say, something like this:

def main():
    (your main code)
    main()
main()

though generally while loops are much cleaner and don't require global variables :)

Upvotes: 0

Robert Peters
Robert Peters

Reputation: 4104

from http://www.swaroopch.com/notes/Python_en:Control_Flow

#!/usr/bin/python
# Filename: while.py

number = 23
running = True

while running:
    guess = int(input('Enter an integer : '))

    if guess == number:
        print('Congratulations, you guessed it.')
        running = False # this causes the while loop to stop
    elif guess < number:
        print('No, it is a little higher than that.')
    else:
        print('No, it is a little lower than that.')
else:
    print('The while loop is over.')
    # Do anything else you want to do here

print('Done')

Upvotes: 2

Related Questions