0

Below is the code I have been working on. I am new to python and programing and have been trying to teach myself.

I get the following error. But messages is defined so I don't understand.

[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

code:

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)

I have "messages defined" so I dont know why I am getting an error telling me "messages" is not define.

0

1 Answer 1

9

Because the line write_csv('twitter_gmail.csv', messages, append=True) is not part of the main() function. The line has not been indented at all, so Python sees it as a separate line of code following the main() function, and executes it immediately when you run this script.

Indent that line to match the messages line, and don't forget to call 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()
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much. That makes total sense to call main (). As I have been teaching myself to code , this site has helped me so much. Really appreciate it!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.