6

Get User Input in Python

 3 years ago
source link: https://www.devdungeon.com/content/get-user-input-python
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Submitted by NanoDano on Wed, 02/12/2020 - 21:33

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK