简体   繁体   中英

I cannot import function name from another file

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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM