【问题标题】:Global name 'parseLog' not defined Python 2.7全局名称“parseLog”未定义 Python 2.7
【发布时间】:2015-04-16 12:34:56
【问题描述】:

我已经阅读了类似的主题,但我仍然不确定我做错了什么。我收到错误消息,未定义全局名称“parseLog”。另外,我一直在摸索这里的代码格式是否正确,但是我的编辑器中的所有内容都正确缩进了,只是因为试图在这里这样做而感到恼火。

import urllib2
import re
import json
class parseLog:
    def __init__(self):
        ''' Get access log location and pattern(Common Log Format)'''

    self.apacheLog = 'https://raw.githubusercontent.com/access.log'
    self.data = urllib2.urlopen(self.apacheLog)
    self.parts = [
    r'(?P<host>\S+)', 
    r'\S+', 
    r'(?P<user>\S+)', 
    r'\[(?P<time>.+)\]',
    r'"(?P<request>.+)"', 
    r'(?P<status>[0-9]+)', 
    r'(?P<size>\S+)', 
    r'"(?P<referer>.*)"', 
    r'"(?P<agent>.*)"', 
    ]

    self.pat = re.compile(r'\s+'.join(self.parts)+r'\s*\Z')

def rescheck(result):
    '''Check for absent refer page'''
    if result["referer"] == "-":
        result["referer"] = None
    return
def getIPinfo(IP,result):
    '''Get lat,long,org,and ISP using IP address from log record'''
    apiURL = 'http://ip-api.com/json/'+IP            
    getResp = urllib2.urlopen(apiURL)
    jsonResp = json.load(getResp)
    result["lat"] = jsonResp['lat']
    result["long"] = jsonResp['lon']
    result["org"] = jsonResp['org']
    result["ISPname"] = jsonResp['isp']
    finalKeys = ["time","request","referer","host","org","lat","long","ISPname"]
    finalDict = {x: result[x] for x in finalKeys if x in result}
    print finalDict
    return finalDict
def main():
    with open('C:\Users\Brandon\Downloads\LogCopy1.txt','a') as f:
        for line in parseLog.data:
            match = parseLog.pat.match(line)
            result = match.groupdict()
            theIP = result["host"]
            print theIP
            parseLog.rescheck(result)
            dictToWrite = parseLog.getIPinfo(theIP,result)
            f.write(str(dictToWrite))
            #print str(dictToWrite)
main()

【问题讨论】:

    标签: python class global-variables


    【解决方案1】:

    parseLog 是一个类。为了在 python 中访问一个类的数据成员或方法(除非它是静态的),你首先需要创建一个类的实例:

    pl = parseLog()
    

    然后更新您的代码:

    def main():
        pl = parseLog()
        with open('C:\Users\Brandon\Downloads\LogCopy1.txt','a') as f:
            for line in pl.data:
                match = pl.pat.match(line)
                result = match.groupdict()
                theIP = result["host"]
                print theIP
                rescheck(result)
                dictToWrite = getIPinfo(theIP,result)
                f.write(str(dictToWrite))
    

    【讨论】:

    • 当我尝试这个时,我仍然遇到同样的错误。其他一切看起来都还好吗?
    • @RagePwn 您的 __init__ 实现未缩进。如果不是帖子中的错误,那会引起问题吗?
    • 帖子里只有这样。所有定义都在我的代码中正确缩进,我只是很难在我的第一篇文章中正确格式化它。
    • @RagePwn 还有其他你没有发布的代码吗?您发布的带有我的答案更改的代码对我来说编译得很好(尽管您的 URL 给出了 HTTP 错误 400)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-03
    • 2013-08-23
    • 2013-11-12
    • 2014-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多