In this tutorial, we will check how to get user input from the shell, using Python on the Raspberry Pi.
Using the shell to interact with the user is one of simplest interfaces, but it’s still very useful. Doing it in a Python program is very simple, as we will see below.
The program we are going to develop will simply accept user input from the command line and print it. This logic will be done in an infinite loop. If the user writes the string “exit”, then we will break the loop and finish the program execution.
Note that although we are testing this on a Raspberry Pi, this should work in a regular computer with an installation of Python.
The code for this tutorial is very simple and we don’t need to include any module, since all the functions we are going to use are available by default.
As already mentioned in the introductory section, we will get the user input in an infinite loop.
while True: #input handling code
Now, to get the user input from the command line, we simply need to use the input function.
This function call receives as input a string, which will be printed to the shell, and then waits for a line to be typed by the user. Once the user types a line, this function returns what was typed as a string.
userInput = input("write something:\n")
Now that we have obtained the string written by the user, we will check if he has typed the word “exit“. As we have mentioned in the introductory section, this will be our loop stopping condition.
To break the loop, we simply need to use the break statement.
if userInput == "exit": break
In case we did not break the loop, the we print the user input. After that, the program execution will go back to the beginning of the loop, asking for user input again.
print("You have written: " + userInput)
The final source code can be seen below.
while True: userInput = input("write something:\n") if userInput == "exit": break print("You have written: " + userInput)
To test the code, simply run the previous Python program in the environment of your choice. In my case, I’m using IDLE to run it.
Figure 1 illustrates the behavior of the program. As can be seen, upon running the program, the string we passed to the input function is presented to the user. In our case, it is simply asking the user to write something.
When the user writes some content and presses enter, we print what was inputted. Since this is being done on an infinite loop, then the user is again prompted to write more content, as can be seen.
When the user writes the word “exit“, then the program finishes the execution, as expected.
Figure 1 – Getting user input from the Python shell.