Python“变量未定义”错误

时间:2013-12-07 19:24:04

标签: python python-2.7

以下是我一直在处理的代码。我是python和编程的新手,并一直在努力自学。

我收到以下错误。但messages已定义,所以我不明白。

[ec2-user@ip-172-31-46-164 ~]$ ./twitter_test16.sh
Traceback (most recent call last):
  File "./twitter_test16.sh", line 53, in <module>
    write_csv('twitter_gmail.csv', messages, append=True)
NameError: name 'messages' is not defined

代码:

import csv
import json
import oauth2 as oauth
import urllib
import sys
import requests
import time

CONSUMER_KEY = ""
CONSUMER_SECRET = ""
ACCESS_KEY = ""
ACCESS_SECRET = ""

class TwitterSearch:
    def __init__(self,
        ckey    = CONSUMER_KEY,
        csecret = CONSUMER_SECRET,
        akey    = ACCESS_KEY,
        asecret = ACCESS_SECRET,
        query   = 'https://api.twitter.com/1.1/search/tweets.{mode}?{query}'
    ):
        consumer     = oauth.Consumer(key=ckey, secret=csecret)
        access_token = oauth.Token(key=akey, secret=asecret)
        self.client  = oauth.Client(consumer, access_token)
        self.query   = query

    def search(self, q, mode='json', **queryargs):
        queryargs['q'] = q
        query = urllib.urlencode(queryargs)
        return self.client.request(self.query.format(query=query, mode=mode))

def write_csv(fname, rows, header=None, append=False, **kwargs):
    filemode = 'ab' if append else 'wb'
    with open(fname, filemode) as outf:
        out_csv = csv.writer(outf, **kwargs)
        if header:
            out_csv.writerow(header)
        out_csv.writerows(rows)

def main():
    ts = TwitterSearch()
    response, data = ts.search('@gmail.com', result_type='recent')
    js = json.loads(data)


    # I need to parse the content in js and turn it into a generator expression
    messages = ([msg['created_at'], msg['txt'], msg['user']['id']] for msg in js.get('statuses', []))
    #

write_csv('twitter_gmail.csv', messages, append=True)

我有“消息已定义”所以我不知道为什么我收到错误告诉我“消息”未定义。

1 个答案:

答案 0 :(得分:8)

因为行write_csv('twitter_gmail.csv', messages, append=True) 不是main()函数的一部分。该行根本没有缩进,因此Python将其视为main()函数之后的单独代码行,并在运行此脚本时立即执行。

缩进该行以匹配messages行,并且不要忘记调用 main()

def main():
    ts = TwitterSearch()
    response, data = ts.search('@gmail.com', result_type='recent')
    js = json.loads(data)

    messages = ([msg['created_at'], msg['txt'], msg['user']['id']] for msg in js.get('statuses', []))
    write_csv('twitter_gmail.csv', messages, append=True)

if __name__ == '__main__':
    main()