2

I am trying to write a method that I can call in a different script, however, I am not able to successfully call the script(s) with the way I have it written. This is one of the scripts I am trying to call (the second is very similar:

#!usr/bin/env python

import re
import urllib
from datetime import datetime
from datetime import timedelta

date = datetime.now()
date1 = date + timedelta(days=1)
date2 = date + timedelta(days=2)


class city :
        def __init__(self, city_name, link) :
                self.name = city_name
                self.url = link
                self.wind1 = 0

    def retrieveTemps(self) :
            filehandle = urllib.urlopen(self.url)

            # get lines from result into array
            lines = filehandle.readlines()

            # (for each) loop through each line in lines
            line_number = 0 # a counter for line number
            for line in lines:
                    line_number = line_number + 1 # increment counter

                    # find string, position otherwise position is -1

                    position2 = line.rfind('<ul class="stats">')

                    #String is found in line

                    if position2 > 0 :
                            self.wind0 = lines[line_number + 1].split('</strong>')[0].split('style="">')[-1]

                            break # done with loop, break out of it

            return ('c.wind0')

            filehandle.close()

m1 = city('Mexico City', 'http://www.accuweather.com/en/mx/mexico-city/242560/daily-weather-forecast/242560?day=2')
m3 = city('Veracruz', 'http://www.accuweather.com/en/mx/veracruz/236233/daily-weather-forecast/236233?day=2')
m5 = city('Tampico', 'http://www.accuweather.com/en/mx/tampico/235985/daily-weather-forecast/235985?day=2')
m7 = city('Nuevo Laredo', 'http://www.accuweather.com/en/mx/nuevo-laredo/235983/daily-weather-forecast/235983?day=2')
m9 = city('Monterrey', 'http://www.accuweather.com/en/mx/monterrey/244681/daily-weather-forecast/244681?day=2')
m11 = city('S. Luis Potosi', 'http://www.accuweather.com/en/mx/san-luis-potosi/245369/daily-weather-forecast/245369?day=2')
m13 = city('Queretaro', 'http://www.accuweather.com/en/mx/queretaro/245027/daily-weather-forecast/245027?day=2')
m15 = city('Laz. Cardenas', 'http://www.accuweather.com/en/mx/lazaro-cardenas/239054/daily-weather-forecast/239054?day=2')

cities = []
cities.append(m1)
cities.append(m3)
cities.append(m5)
cities.append(m7)
cities.append(m9)
cities.append(m11)
cities.append(m13)
cities.append(m15)

I try to call this script and another script with this:

#!usr/bin/env python

from script import getCities
from script2 import getWind

cities = getCities()
wind = getWind()

for c in wind :
        c.retrieveTemps()
for c in cities :
        c.retrieveTemps()

print(c.name,c.high0,c.low0,c.high1,c.low1,c.weather0,c.weather1,c.wind0,c.wind1)

c.wind0 is found with script2, while all the other variables are found with script1. If I import script1 second, I get the error: AttributeError: city instance has no attribute 'wind1', which has no attribute with script2, it is associated with script1. It seems to be ignoring the first script I import.

Any suggestions would be appreciated. Thanks!

UPDATE:

Using your suggestions, plus something else, I came up with this and it works perfectly.

#!usr/bin/env python

import script1
import script2

wind = script2.getWind()
cities = script.getCities()

for c in cities :
        c.retrieveTemps()
for w in wind :
        w.retrieveWind()

# iterate over both lists in parallel, zip returns a tuple 
for c, w in zip(cities, wind) :
    print(c.name,c.high0,c.low0,c.high1,c.low1,c.weather0,c.weather1,c.wind0,w.wind1)

Thanks everyone for your help!

2
  • 5
    You're importing city, but not cities. Commented Sep 13, 2013 at 18:31
  • Alright, I changed the script to import both city and cities, but I am having another problem that I restated in the original post. Commented Sep 13, 2013 at 18:47

3 Answers 3

1

Make everything below the class a function that returns cities, import the function, and call it, setting cities to a new local variable. Then you can run your for loop.

Disclaimer: I didn't test this at all.

Step1:

def getCities():
    m1 = city('Mexico City', 'http://www.accuweather.com/en/mx/mexico-city/242560/daily-weather-forecast/242560?day=2')
    m3 = city('Veracruz', 'http://www.accuweather.com/en/mx/veracruz/236233/daily-weather-forecast/236233?day=2')
    m5 = city('Tampico', 'http://www.accuweather.com/en/mx/tampico/235985/daily-weather-forecast/235985?day=2')
    m7 = city('Nuevo Laredo', 'http://www.accuweather.com/en/mx/nuevo-laredo/235983/daily-weather-forecast/235983?day=2')
    m9 = city('Monterrey', 'http://www.accuweather.com/en/mx/monterrey/244681/daily-weather-forecast/244681?day=2')
    m11 = city('S. Luis Potosi', 'http://www.accuweather.com/en/mx/san-luis-potosi/245369/daily-weather-forecast/245369?day=2')
    m13 = city('Queretaro', 'http://www.accuweather.com/en/mx/queretaro/245027/daily-weather-forecast/245027?day=2')
    m15 = city('Laz. Cardenas', 'http://www.accuweather.com/en/mx/lazaro-cardenas/239054/daily-weather-forecast/239054?day=2')


    cities = []
    cities.append(m1)
    cities.append(m3)
    cities.append(m5)
    cities.append(m7)
    cities.append(m9)
    cities.append(m11)
    cities.append(m13)
    cities.append(m15)

    return cities

Step 2:

from script1 import getCities

Step 3:

cities = getCities()

for c in cities :
    c.retrieveTemps()
    print(c.name,c.high0,c.low0,c.high1,c.low1,c.weather0,c.weather1,c.wind0,c.wind1)    
Sign up to request clarification or add additional context in comments.

5 Comments

Sorry. I am new at python and not exactly sure how I would do this.
When I do that it gives me the follow error for the line "cities = script1.getCities()"...'NameError: name 'script1' is not defined'
Oh, I guess get rid of script1 and just use getCities(). Yeah, I don't use Python much...
ok. That fixed that. However, I am still having the same error I had in part 2 of my original post. I am calling it with the code I added in to the original post:
Okay, so first of all, retrieveTemps() is returning the string 'c.wind0'. I assume you want it to actually return the value of self.wind0 or a list or something. Then, when you loop through the cities, you need to set a variable to c.retrieveTemps() or else the output of the function goes nowhere. You'll probably want to be appending to a list the values of c.retrieveTemps() as you loop. Then you can use the values from that list in your print statement.
1

In your main script you use the variable c to reference a "wind" and then "cities". It the end of the loops the variable c will now reference the last city from the cities list. Therefore it won't have any "wind" attributes.

Comments

0

If it was me, i would copy and paste the method from the first file to the file you're using right now, because as far as i know, there isn't a way to call a method from a different script, not sure,maybe there is, but the easiest thing for me would be to copy and paste the method. hope i helped... :)

5 Comments

A fundamental ability of all good programming languages is the ability to call external methods. This is what import is all about: including external methods into memory to help execution of a script. Every coding language is in fact no more than an engine that understands its own language and a series of external methods written by the author of that language that breaks advanced functions (like Python's lower(), which turns all letters in a string to lower case) into smaller functions, so that you don't have to code everything yourself all the time.
@JWarner112 ok, i understand, but i've only been programming python for about a month, so i thought that it's not possible, but apparently i've been proven wrong... i'll keep that in mind next time
It's no problem, my friend. We're all learning! I just started Python a month and a half ago myself, but I've dedicated a lot of time to it. Besides, this is an overarching concept of programming in general, and those can be even harder to grasp. Try the Codecademy Python tutorial here. It doesn't work perfectly, but you can write your code here and manipulate the URLs to get through it all :)
@JWarner112 i dedicated at least 3 hours a day, usually 5 or more, i've done about 44% of the python in codecademy, it's a good website, and at the moment i'm learning from a book called python programming for the absolute beginner, it's pretty good. i'd recommend getting it, it teaches python 3.1.1. also, i used codecademy ages ago to start learning java, but it was a few years back i didn't understand it, i might return to java later, my friend said he can teach me it
@JWarner112 the book it bigger than A5 but smaller than A4, 432 pages or so, and explained in detail, there's a second one in the series called more python programming for the absoluute beginner, and it introduces even more modules like pygame :)

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.