0

I am making a password generator that turns the generated password into an md5 hash, but it will not allow me to import a function from one file to another.

Here is my code.

password.py

import random
import string


def main():

    y = int(input("Enter desired length for password: "))

    def random_char(y):
        return ''.join(random.choice(string.ascii_letters + string.digits + string.punctuation) for x in range(y))

    genpass = random_char(y)

    print(genpass)

    def getGenpass():
        return genpass

main()

hash.py

import hashlib
import password
from password import getGenpass


mystring = password.getGenpass()

def main():
    hash_object = hashlib.md5(mystring.encode())
    print("Here is your md5 hash: " + hash_object.hexdigest())

main()

If I remove the imports from password.py the script does work.

disclaimer. I am new to python.

Deadfly
  • 3
  • 1

3 Answers3

0

Because your function ist no global, its defined in the main() and its not reachable from outer the main. Also your main always runs on each import. When you only want to use that as an import then try this:

password.py:

import random
import string

def getGenpass():

    def random_char(y):
        return ''.join(random.choice(string.ascii_letters + string.digits + string.punctuation) for x in range(y))

    y = int(input("Enter desired length for password: "))

    genpass = random_char(y)

    print(genpass)

    return genpass

And then import only the function in your hash.py:

import hashlib
from password import getGenpass
micharaze
  • 957
  • 8
  • 25
  • That solved my issue, thank you very much. I was not aware that the def main() would make it so it wasn't global! – Deadfly Oct 16 '19 at 03:22
0

password.py

you can code like this:

import random
import string

def getGenpass():
    y = int(input("Enter desired length for password: "))

    def random_char(y):
        return ''.join(random.choice(string.ascii_letters + string.digits + string.punctuation) for x in range(y))

    genpass = random_char(y)
    print(genpass)
    return genpass
micharaze
  • 957
  • 8
  • 25
Leslie
  • 41
  • 2
0

getGenpass is an inner function inside Main, why are you expecting that it will be visible?

Rem
  • 1
  • 2