全局变量的问题,泡菜,诸如此类的东西



这是我的第一篇文章。我得到错误:

Traceback (most recent call last):
File "<input>", line 1, in <module>
File "intruder.py", line 47, in <module>
    main()
File "intruder.py", line 16, in main
    readfile()
File "intruder.py", line 34, in readfile
    pickle.load(f)
File "/usr/lib/python2.7/pickle.py", line 1378, in load
    return Unpickler(file).load()
File "/usr/lib/python2.7/pickle.py", line 858, in load
    dispatch[key](self)
File "/usr/lib/python2.7/pickle.py", line 880, in load_eof
    raise EOFError
EOFError

对于代码:

#!/usr/bin/python
import getpass
import bz2
import pickle
import marshal
import os, sys
global data
global firsttime
global password
global user
fp = open("firsttime.txt", "r")
data = fp.read();
firsttime = data
def main():
    readfile()
    name = raw_input('What is your name? ')
    if name == user:
        user_input = getpass.getpass('Enter Password: ')
        if user_input != password:
            print "Intruder alert!"
            main()
    if name != user:
        print "Intruder alert!"
        main()
    print "Login Successful! "
def savefile():
    n = open("settings.pkl", 'wb')
    pickle.dump(user, n, 2)
    pickle.dump(password, n, 2)
    n.close()
def readfile():
    f = open("settings.pkl", "rb")
    pickle.load(f)
    f.close()
if data < 1:
    user = raw_input ("Enter desired username: ")
    password = getpass.getpass('Enter desired password: ')
    # encrypted_password = bz2.compress(password)
    # bz2.decompress(encrypted_password)
    data = 2
    g = open("firsttime.txt", "rb")
    outf.write(g(data))
    g.close()
    savefile()
if data > 1:
    main()

编辑:我解决了上面的问题。我改了:

fp = open("firsttime.txt", "r")

至:

fp = file("firsttime.txt", "r")

现在它显示了错误:

Traceback (most recent call last):
    File "intruder.py", line 47, in <module>
        main()
    File "intruder.py", line 17, in main
    if name == user:
NameError: global name 'user' is not defined

这很奇怪,因为user被定义为用户的raw_input,并且它在这个错误出现之前就向我请求它。

global关键字告诉Python您引用的是全局变量。它不会创建变量。

您需要更改为以下内容。

全局defs,删除您拥有的global data定义,并替换为:

data = None
firsttime = None
password = None
user = None

然后在函数中告诉Python,您引用的是全局变量,而不是局部变量。这只需要写入变量,而不是从中读取

def main():
    global user, firsttime, password, user
<snip>
def savefile():
    global user, firsttime, password, user
<snip>
def readfile():
    global user, firsttime, password, user
<snip>

除此之外,代码还有其他问题(fp从未关闭等),但我不会批评其他问题。

最新更新