1

这是我的第一篇文章。我收到错误消息:

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

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

4

1 回答 1

0

global关键字告诉 Python 你正在引用一个全局变量。它不会创建变量。

您需要更改为以下内容。

全局定义,删除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 永远不会关闭等),但我不会评论其他问题。

于 2014-03-28T01:45:26.003 回答