Get User Input in Python

Advertisement

Advertisement

Introduction

There are a few ways to get user keyboard input from the terminal:

  • Using the input() function
  • using sys.stdin directly
  • Getting a password with getpass.getpass()

Let's look at each one now.

Get a single line of input

The input() function in Python will let a user type in something to the terminal and press the return key. Everything the user entered up to the return key will be recorded and stored as the return value. For Python 2 it is raw_input().

data_entered = input('Please enter some text: ')
print(data_entered)

For more details, see https://docs.python.org/3/library/functions.html#input.

Accessing sys.stdin directly

sys.stdin is a file-like object so you can do the typical read() and readlines() functions. Here are a few functions available:

  • sys.stdin.read() - This function can read multiple lines until a certain number of bytes (if specified) have been read or EOF. For example, sys.stdin.read(5) will read they keys: a<return>b<return>cdef<return> as a\nb\nc and ignoring anything past the last byte read until the last return press.
  • sys.stdin.readlines() will read standard input line-by-line until EOF is reached.

For more details about sys.stdin see https://docs.python.org/3/library/sys.html#sys.stdin.

import sys

text = sys.stdin.read(10)  # Read 10 bytes
print(text)
import sys

lines = sys.stdin.readlines()
print(lines)

Get a password with getpass

The getpass.getpass() function will not echo out the keyboard text a user enters, so when they type in a password, it won't be visible to everyone. It will still return a regular string though that can be printed out if desired. It is not any more secure than hiding the keyboard input.

from getpass import getpass

# `getpass()` will hide the keyboard text from display
password = getpass()
print(password)

For more details see https://docs.python.org/3/library/getpass.html#getpass.getpass.

More about standard input, output, and error

If you want to learn more about standard input, output, and error in general, and how to redirect and pipe data, check out my tutorial: STDIN, STDOUT, STDERR, Piping, and Redirecting.

Conclusion

After reading this guide you should understand how to get user input using the input() function, from sys.stdin directly, and a get password using getpass.getpass().

References

Advertisement

Advertisement