0

I try to use a seperate Module with a getpass() function in it, e.g.

#! /usr/bin/python3
from getpass import getpass
import sys
def mypass():
    try:
        password = getpass('Password: ')
    except Exception as e:
        print(e)
        sys.exit(1)
    while password == '':
        password = getpass('Enter password again: ')
    return(password)
mypass()

I have a main script that uses this module:

#! /usr/bin/python3
import myModule
...
def main():
    p = myModule.mypass()
    print(p) #for testing only
...
if __name__ == '__main__':
    main()

When I run the myModule script directy, the password input works at the first try, when I use the main script, password input works at the second try:

user@server:~$./myModule.py
Password:
user@server:~$
user@server:~$./main.py
Password:
Password:
secret
user@server:~$

Does someone knows why and can help me to fix this?

mxFrank
  • 11
  • 3

1 Answers1

0

The problem is that you are always calling the mypass function inside myModule. This happens also when you import it from the main module.

This is why you don't see the password printed to the terminal on the first time when running the main.py file.

You should put the mypass() function call in the myModule inside the if name == "main" guard.

Change the code inside myModule to the following:

from getpass import getpass
import sys

def mypass():
    try:
        password = getpass('Password: ')
    except Exception as e:
        print(e)
        sys.exit(1)
    while password == '':
        password = getpass('Enter password again: ')
    return password

if __name__ == '__main__':
    password = mypass()
    print(password)

Now the mypass function won't be called when the myModule is imported.

varajala
  • 111
  • 4