Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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

Example:

import threading
import queue

defconsole(q):
    while1:
        cmd = input('> ')
        q.put(cmd)
        if cmd == 'quit':
            breakdefaction_foo():
    print('--> action foo')

defaction_bar():
    print('--> action bar')

definvalid_input():
    print('---> Unknown command')

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

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

    while1:
        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

defconsole(q, lock):
    while1:
        input()   # Afther pressing Enter you'll be in "input mode"with lock:
            cmd = input('> ')

        q.put(cmd)
        if cmd == 'quit':
            breakdefaction_foo(lock):
    with lock:
        print('--> action foo')
    # other actionsdefaction_bar(lock):
    with lock:
        print('--> action bar')

definvalid_input(lock):
    with lock:
        print('--> Unknown command')

defmain():
    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()

    while1:
        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".

Solution 2:

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

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

number = 23
running = Truewhile running:
    guess = int(input('Enter an integer : '))

    if guess == number:
        print('Congratulations, you guessed it.')
        running = False# this causes the while loop to stopelif 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 hereprint('Done')

Solution 3:

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

deftimes(f): # f: file descriptor
    after = 0whileTrue:
        changes = select.select([f], [], [], 1)

        if f in changes[0]:

            data = f.readline().strip()

            if data == "q":
                breakelse:
                print"After", after, "seconds you pressed", data

        after += 1

times(sys.stdin)

Solution 4:

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

Solution 5:

if you want to get input repeatedly from user;

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

and based on inp you can perform any condition.

Post a Comment for "Constantly Looking For User Input In Python"