python - Python 局部变量与全局变量

标签 python

我是编程新手,想知道这是否可行。我正在尝试创建一个受密码保护的脚本,其中输入密码一次,然后需要在下次打开脚本时继续执行该脚本。我将密码存储在文件中并对其进行加密,然后在下次打开脚本时检查该文件是否存在。我遇到的问题是检查密码是否匹配,因为原始密码在函数中作为局部变量。

def createFile():
    pw = input('Enter Password: ')
    pw2 = input('ReType Password: ')
    if pw == pw2:        
        newPw = encrypt(pw, 10)  #encodes the string with a key in a seperate encrypt function
        pwFile = open('PW.txt', 'a')
        pwFile.write(newPw)
        pwFile.close()
    else:
        print('The passwords do not match')
        createFile()


if os.path.isfile('PW.txt'):
    print('File exists')
    pwCheck = input('What is the password? ')
    #I can not check pwCheck == pw since pw is a local var.

    #progression of script here
else:
    createFile()

我知道将局部变量设置为全局变量被认为是不好的。有没有办法重组我迄今为止所拥有的一切来使这项工作发挥作用?当我写这篇文章时,我想我可能已经想出了一个可能的解决方案,但我现在没有时间测试它。我是否使用 pwCheck 的相同 key 运行相同的加密函数,然后检查它是否 == 到 PW.txt 的第一行?这是正确的和/或还有其他解决方案吗?

谢谢。

使用 Windows、Python 3.4

最佳答案

也许可以使用单向哈希来代替“加密”。然后,您可以对随后输入的密码进行哈希处理,并将其与文件中存储的哈希进行检查...类似:

def createFile():
    pw = input('Enter Password: ')
    pw2 = input('ReType Password: ')
    if pw == pw2:        
        newPw = sha.new(pw).digest
        pwFile = open('PW.txt', 'a')
        pwFile.write(newPw)
        pwFile.close()
    else:
        print('The passwords do not match')
        createFile()


if os.path.isfile('PW.txt'):
    print('File exists')
    pwCheck = input('What is the password? ')
    previous = open('PW.txt', 'r')
    prevPass = previous.read()
    hashed = sha.new(pwCheck).digest()
    if (hashed==prevPass):
        #progression of script here
else:
    createFile()

关于python - Python 局部变量与全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27532746/

相关文章:

python - 检查字符串是否可以在 Python 中转换为 float

python - 使用 for 循环将两个列表中的数据插入到字典中

python - 根据条件用不同的替换字典替换 Pandas 数据框列中的值

Python:对没有 if 子句的非空列表的迭代结果为空。为什么?

python - 如何在 PyQt 中获取命名颜色?

python - 删除 lxml 中的所有命名空间?

当超过 100 个样本时,Python K-means 无法拟合数据

python - 从字符串列表中删除字符

python - 在 Python 中将解析时间与今天的日期结合起来

python - pep8 "mixed spaces and tabs"错误与 "under-indented for visual indent"冲突