IT Learning

実践形式でITのお勉強

Python

【Python】How to input password in python by getpass

投稿日:

Description

When you need to input your ID and Password for certification by program, It’s not good idea to write them as plaintexts in your source code because of security reason. It’s safer to let human to input them at each time.

In python, you can use input function for it, but there is a problem the password characters you are inpurting is showed at the screen. Alternatively you can use getpass function hide the characters and now we show the way to use it.

Example of input function

Firstly, we are showing the example of input function.

when input function is executed, it can wait to be input some characters. So we can input password characters ineractively.

pw = input()

But there is a probem such as characters you are inputting are not hided like following example image.

And after executing the function, the results is also showed.

Example of getpass function

To avoid that we alternatively use getpass function that is spezialize to input characters we don’t show.

import getpass
pw = getpass.getpass()

This function can hide characters being inputed when you are doing.

And the results is also hided.

The getpass function is so useful and if you want to print some words when the function is waiting for input, to be set the the prompt option.
getpass.getpass(prompt='Input your password:')

Sumary

  • The getpass function is better solution for inputing password interactively.

Related

-Python

執筆者:


comment

Your email address will not be published. Required fields are marked *