Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Calling this script
#1
Hello,

I'm trying to figure out how to call the
#print data part
of my Weather.py script into another script I have.
I tried making a function for the print statements
def displayData():
    # print data
    print("Weather for:", data["region"])
    print("Now:", data["dayhour"])
    print(f"Temperature now: {data['temp_now']}°C")
    print("Description:", data['weather_now'])
    print("Precipitation:", data["precipitation"])
    print("Humidity:", data["humidity"])
    print("Wind:", data["wind"])
    print("Next days:")
    for dayweather in data["next_days"]:
        print("="*40, dayweather["name"], "="*40)
        print("Description:", dayweather["weather"])
        print(f"Max temperature: {dayweather['max_temp']}°C")
        print(f"Min temperature: {dayweather['min_temp']}°C")
and tried calling it like:
from Weather import displayData
but that did not work.

Any idea's on how to get this to work?

Any help is greatly appreciated, thanks.

My Weather.py Code:
from bs4 import BeautifulSoup as bs
import requests

USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36"
# US english
LANGUAGE = "en-US,en;q=0.5"

def get_weather_data(url):
    session = requests.Session()
    session.headers['User-Agent'] = USER_AGENT
    session.headers['Accept-Language'] = LANGUAGE
    session.headers['Content-Language'] = LANGUAGE
    html = session.get(url)
    # create a new soup
    soup = bs(html.text, "html.parser") 

    # store all results on this dictionary
    result = {}
    # extract region
    result['region'] = soup.find("div", attrs={"id": "wob_loc"}).text
    # extract temperature now
    result['temp_now'] = soup.find("span", attrs={"id": "wob_tm"}).text
    # get the day and hour now
    result['dayhour'] = soup.find("div", attrs={"id": "wob_dts"}).text
    # get the actual weather
    result['weather_now'] = soup.find("span", attrs={"id": "wob_dc"}).text

    # get the precipitation
    result['precipitation'] = soup.find("span", attrs={"id": "wob_pp"}).text
    # get the % of humidity
    result['humidity'] = soup.find("span", attrs={"id": "wob_hm"}).text
    # extract the wind
    result['wind'] = soup.find("span", attrs={"id": "wob_ws"}).text

    # get next few days' weather
    next_days = []
    days = soup.find("div", attrs={"id": "wob_dp"})
    for day in days.findAll("div", attrs={"class": "wob_df"}):
        # extract the name of the day
        day_name = day.findAll("div")[0].attrs['aria-label']
        # get weather status for that day
        weather = day.find("img").attrs["alt"]
        temp = day.findAll("span", {"class": "wob_t"})
        # maximum temparature in Celsius, use temp[1].text if you want fahrenheit
        max_temp = temp[0].text
        # minimum temparature in Celsius, use temp[3].text if you want fahrenheit
        min_temp = temp[2].text
        next_days.append({"name": day_name, "weather": weather, "max_temp": max_temp, "min_temp": min_temp})
    # append to result
    result['next_days'] = next_days
    return result

if __name__ == "__main__":
    URL = "https://www.google.com/search?lr=lang_en&ie=UTF-8&q=weather"
    import argparse
    parser = argparse.ArgumentParser(description="Quick Script for Extracting Weather data using Google Weather")
    parser.add_argument("region", nargs="?", help="""Region to get weather for, must be available region.
                                        Default is your current location determined by your IP Address""", default="")
    # parse arguments
    args = parser.parse_args()
    region = args.region
    URL += region
    # get data
    data = get_weather_data(URL)

    # print data
    print("Weather for:", data["region"])
    print("Now:", data["dayhour"])
    print(f"Temperature now: {data['temp_now']}°C")
    print("Description:", data['weather_now'])
    print("Precipitation:", data["precipitation"])
    print("Humidity:", data["humidity"])
    print("Wind:", data["wind"])
    print("Next days:")
    for dayweather in data["next_days"]:
        print("="*40, dayweather["name"], "="*40)
        print("Description:", dayweather["weather"])
        print(f"Max temperature: {dayweather['max_temp']}°C")
        print(f"Min temperature: {dayweather['min_temp']}°C")
My Main Code I want to import my Weather Script into:
#!/usr/bin/env python3

import json
import random
import datetime
import operator
import requests
from bs4 import BeautifulSoup
from Weather import *
import wikipedia
import wolframalpha
import pyttsx3
import espeakng
import speech_recognition as sr 

Commander = "Commander"
print ("Initializing B.A.X.T.E.R...")

def speak(text):
    mySpeaker = espeakng.Speaker()
    #mySpeaker.say('Initializing Baxter')
    

def wishMe():
    hour = int(datetime.datetime.now().hour)
    if hour>=0 and hour<12:
        speak("Good Morning" + Commander)
        print("Good Morning " + Commander)
    elif hour>=12 and hour<18:
        speak("Good Afternoon" + Commander)
        print("Good Afternoon " + Commander)   
    else:
        speak("Good Evening" + Commander) 
        print("Good Evening " + Commander) 
        speak("How may I be of service?")
        print("How may I be of service?")   

def listenCommand():
    command=0
    hear = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listening...")
        audio = hear.listen(source)
#---------------------------
# Uses google API to listen
    try:
        print("Recognizing...")
        command = hear.recognize_google(audio, language='en-in')
        print(f'{Commander} : {command}\n')

    except:
            pass

    return command 

#--------------------------------

speak("Initializing Baxter..........")
wishMe()

def main():
    command = listenCommand()
    command=str(command).lower()

    #-------------------------------------------------------------------------------------
                            #Search Wikipedia (General Info)
    #-------------------------------------------------------------------------------------
    if ('who is' in command) or ('what is the' in command) or ('what is a' in command):
        speak('Searching Wikipedia...')
        command = command.replace("who is","")
        command = command.replace("what is the","")
        command = command.replace("what is a","")
        results = wikipedia.summary(command, sentences = 2)
        print("Baxter:",results)
        return speak(results) 
    #-------------------------------------------------------------------------------------
                    #Search Wolfram Alpha (Math/Conversions, Definitions)
    #-------------------------------------------------------------------------------------
    elif ('calculate' in command) or ('what is' in command) or ('define' in command):
        speak('Searching Wolfram Alpha...')
        command = command.replace("calculate","")
        command = command.replace("what is","")
        command = command.replace("define","")
        # Wolframalpha App Id
        appId = 'JH9XHR-W9J76L7H5A'
        # Wolfram Instance
        client = wolframalpha.Client(appId)
        res = client.query(''.join(command))
        results = next(res.results).text
        print("Baxter:",results)
        return speak(results) 
    #-------------------------------------------------------------------------------------
                                    #Search News
    #-------------------------------------------------------------------------------------
    elif ('news' in command):
        speak('Searching news networks...')
        command = command.replace("news","")
        url='https://www.google.com/search?q=windsor+news&client=firefox-b-d&source=lnms&tbm=nws&sa=X&ved=2ahUKEwjFr5SwoJb1AhXELs0KHdabBAEQ_AUoAXoECAEQAw&biw=1024&bih=486'
        results = requests.get(url)
        soup = BeautifulSoup(results.text, 'html.parser')
        headlines = soup.find('body').find_all('h3')
        for x in headlines:
            print("Baxter:",x.text.strip())
        return speak(results) 
    #-------------------------------------------------------------------------------------
                                        #Search Weather
    #-------------------------------------------------------------------------------------
    elif ('weather' in command):
        speak('Searching weather networks...')
        command = command.replace("weather","")
        #call weather print data here
    #-------------------------------------------------------------------------------------


    elif 'stop' in command:
        speak("Shutting Down...")
        return exit()
       
    else:
        return 0 

while True:
    main()  
Reply


Messages In This Thread
Calling this script - by Extra - Jan-03-2022, 08:18 PM
RE: Calling this script - by BashBedlam - Jan-03-2022, 10:02 PM
RE: Calling this script - by Extra - Jan-03-2022, 10:11 PM
RE: Calling this script - by snippsat - Jan-04-2022, 12:39 AM
RE: Calling this script - by Extra - Jan-10-2022, 09:34 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  python script is hanging while calling a procedure in database prasanthi417 4 779 Jan-17-2024, 02:33 PM
Last Post: deanhystad
  crontab on RHEL7 not calling python script wrapped in shell script benthomson 1 2,439 May-28-2020, 05:27 PM
Last Post: micseydel
  Calling a C Func though Pyhon Script using DLL file which is created for C file. CMMouli 4 4,800 Feb-18-2017, 05:06 AM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020