Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getpass.getpass() function in Python not working?

Tags:

python

Running on Windows 7 and using PyCharm 2016.2.3 if that matters at all.

Anyway, I'm trying to write a program that sends an email to recipients, but I want the console to prompt for a password to login.

I heard that getpass.getpass() can be used to hide the input.

Here is my code:

import smtplib
import getpass

import sys

print('Starting...')

SERVER = "localhost"
FROM = "[email protected]"

while True:
    password = getpass.getpass()
    try:
        smtpObj = smtplib.SMTP(SERVER)
        smtpObj.login(FROM, password)
        break
    except smtplib.SMTPAuthenticationError:
        print("Wrong Username/Password.")
    except ConnectionRefusedError:
        print("Connection refused.")
        sys.exit()

TO = ["[email protected]"] 
SUBJECT = "Hello!"
TEXT = "msg text"

message = """\
From: %s
To: %s
Subject: %s

%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)

smtpObj.sendmail(FROM, TO, message)
smtpObj.close()
print("Successfully sent email")

But when I run my code, here is the output:

 Starting...
 /Nothing else appears/

I know the default prompt for getpass() is 'Password:' but I get the same result even when I pass it a prompt string.

Any suggestions?

EDIT: The code continues to run indefinitely after it prints the string, but nothing else appears and no emails are sent.

like image 351
TheDude Avatar asked Oct 12 '16 20:10

TheDude


People also ask

How do I use Getpass in Python?

The getpass() function prints a prompt then reads input from the user until they press return. The input is passed back as a string to the caller. The default prompt, if none is specified by the caller, is “Password:”. The prompt can be changed to any value your program needs.

What is Getpass Getpass Python?

getpass.getpass(prompt='Password: ', stream=None) The getpass() function is used to prompt to users using the string prompt and reads the input from the user as Password. The input read defaults to “Password: ” is returned to the caller as a string.

Is Getpass standard Python library?

There are two functions defined in getpass module of Python's standard library. They are useful whenever a terminal based application needs to be executed only after validating user credentials.


2 Answers

For PyCharm 2018.3 Go to 'Edit Configurations' and then select 'Emulate terminal in output console'.

enter image description here

Answer provided by Abhyudaya Sharma

like image 77
guerda Avatar answered Oct 06 '22 23:10

guerda


The problem you have is that you are launching it via PyCharm, which has it's own console (and is not the console used by getpass)

Running the code via a command prompt should work

like image 35
UnholySheep Avatar answered Oct 07 '22 00:10

UnholySheep