【问题标题】:How to print weather information to the console in python如何在python中将天气信息打印到控制台
【发布时间】:2020-02-19 02:32:30
【问题描述】:

我目前正在 python 中创建一个基于文本的控制台程序,我想添加一个命令来使用邮政编码显示当前天气。我已经尝试过广泛使用谷歌搜索,但似乎找不到任何好的东西。适用于我正在尝试做的事情的解决方案都是使用我不熟悉的技术,这些技术用于使用 python 制作实际的应用程序。目前没有 UI,我是 python 的初学者,所以解决方案的可读性和易于理解性越好。

#import statements
import math#import math
import os#access the operating system
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
import os.path
import time

#end import statement

# welcome user
print("welcome to geeko an all in one desktop helper!")
#end welcome

#variables
username = input("Please enter your username: " )#gets username
sudo = False # sets sudo to false indicating normal privledges
if (username == "Caelin"): # if the user enters the sudo username prompt them for a password
         sudoPassword = input("enter sudo password: ")# prompt for passcode
sudoLn = False #sets sudo line mode to false. this line mode is used for sudo commands
pi = math.pi
loc_id = 'USAL0504'
def wrongLineError():
    if(sudoLn):
        print("You are on the sudo line this is purely for special commands normal commands don't work here type \"switch\" to switch to cmd.ln")
    elif(sudoLn == False and sudo == False):
        print("You do not have sudo priviledges")
    elif(sudoLn == False and sudo == True):
        print("to use sudo commands you must be on the sudo line mode type \'switch\' to switch to the sudo line")

def sendEmailMessageOnly(message, password, recipient):
    send_to_email = recipient # Who you are sending the message to

    server = smtplib.SMTP('smtp.gmail.com', 587) # Connect to the server
    server.starttls() # Use TLS
    server.login(email, password) # Login to the email server
    server.sendmail(email, send_to_email , message) # Send the email
    server.quit() # Logout of the email server

def sendFormattedEmail(password, recipient, subject, message):
    msg = MIMEMultipart()
    msg['From'] = email
    msg['To'] = recipient
    msg['Subject'] = subject

    msg.attach(MIMEText(message, 'plain'))

    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(email, password)
    text = msg.as_string()
    server.sendmail(email, recipient, text)
    server.quit()

def sendMultipleFormattedEmails(password, recipients, subject, message):
    for recipientEmail in recipients:
        msg = MIMEMultipart()
        msg['From'] = email
        msg['To'] = recipientEmail
        msg['Subject'] = subject

        msg.attach(MIMEText(message, 'plain'))

        server = smtplib.SMTP('smtp.gmail.com', 587)
        server.starttls()
        server.login(email, password)
        text = msg.as_string()
        server.sendmail(email, recipientEmail, text)
        server.quit()     

#end variables

print ("Hello " + username + "!")# say special welcome

#check if user is root if so alert them and give them sudo status else alert them and leave sudo at a default of false
if(username == "Caelin" and sudoPassword == "bigGlassRemote"):
    print("Welcome! you are the root user and therefore have elevated priviledges")
    email = input('please enter your email: ')
    password = input("please enter your email password: ")
    print('logging into email...')
    time.sleep(1)
    print("logged into email!")
    sudo = True
else:
    print("You are not the root user and have normal priviledges")

while(True): #run an infinite loop prompting the user for command line inputs
    if(sudoLn == False):
        command = input(username + "-cmd.ln: ") # if sudo line mode if off use the cmd.ln prompt
    else:
        command = input(username + "-cmd.sudo: ") # otherwise prompt with cmd.sudo to indicate you are using sudo line mode

    if(command == 'welcome'): 
        if(sudoLn == False): # checks if you are on cmd line

            print("Hello " + username) # if the welcome command is used say hello *username*

        else: # if you are the sudo line
            wrongLineError()
    elif(command == "switch"): # if the command is switch
        if(sudo): # then check for sudo priviledges

            # togles sudoLn
            if(sudoLn):
                sudoLn = False 
            else:
                sudoLn = True

        else:
            wrongLineError()

    elif(command == 'add'):
        if(sudoLn == False):
            num1 = input("type the first number to add here: ")
            num2 = input("type the second number to add here: ")
            ans = float(num1) + float(num2)
            if(ans == round(ans)):
                print(int(ans))
            else:
                print(ans)
        else:
            wrongLineError()

    elif(command == 'subtract'):
        if(sudoLn == False):
            num1 = input("type the first number to subtract here: ")
            num2 = input("type the second number to subtract here: ")
            ans = float(num1) - float(num2)
            if(ans == round(ans)):
                print(int(ans))
            else:
                print(ans)
        else:
            wrongLineError()

    elif(command == "multiply"):
        if(sudoLn == False):
            num1 = input("type the first number to multiply here: ")
            num2 = input("type the second number to multiply here: ")
            ans = float(num1) * float(num2)
            if(ans == round(ans)):
                print(int(ans))
            else:
                print(ans)
        else:
            wrongLineError()

    elif(command == "divide"):
        if(sudoLn == False):
            num1 = input("type the first number to divide here: ")
            num2 = input("type the second number to divide here: ")
            ans = float(num1)/float(num2)
            if(ans == round(ans)):
                print(int(ans))
            else:
                print(ans)
        else:
            wrongLineError()

    elif(command == "area of circle"):
        if(sudoLn == False):
            r = input("type the radius here: ")
            ans = pi*(float(r)**2)
            if(ans == round(ans)):
                print(int(ans))
            else:
                print(ans)
        else:
            wrongLineError()

    elif(command == "area of rectangle"):
        if(sudoLn == False):
            l = input("type the length here: ")
            h = input("type the width here: ")
            ans = float(l)*float(h)
            if(ans == round(ans)):
                print(int(ans))
            else:
                print(ans)
        else:
            wrongLineError()

    elif(command == "area of triangle"):
        l = input("type the length here: ")
        h = input ("type the height here: ")
        ans = (float(l) * float(h))/2
        if(ans == round(ans)):
            print(int(ans))
        else :
            print(ans)

    elif(command == 'pi'):
        if(sudoln):
            print(pi)
        else:
            wrongLineError()

    elif(command == "edit file anywhere"):
        if(sudoLn):
            path = input("enter the path to the file (if the file doesen't exist it will be created): ")
            file = open(path, "w+")
            Exit = False
            while(not Exit):
                write = input("type what you would like to be written on the document. type !@exit to return to the the command line: ")
                if(write == "!@exit"):
                    file.close()
                    Exit = True
                else:
                    file.write(write)
        else:
            wrongLineError()


    elif(command == "delete file anywhere"):
        if(sudoLn):
            path = input("enter the path to the file you wish to delete: ")
            os.remove(path)
            print(path + "has been removed")
        else:
            wrongLineError()

    elif(command == 'send unformatted email'):
        if(sudoLn):
            recipient = input('enter the recipient\'s email address: ')
            msg = input("enter the content of the email: ")
            print('Sending email...')
            sendEmailMessageOnly(msg, password, recipient)
            print('Email sent!')
        else:
            wrongLineError()

    elif(command == "send formatted email"):
        if(sudoLn):
            subject = input('enter the subject line: ')
            recipient = input('enter the recipient\'s email address. type multiple to send an email to multiple recipients: ')
            if(recipient == 'multiple'):
                sendMultiple = True
                repeat = True
                i = 1
                recipient = []
                while(repeat):
                    newRecipient = input('recipient%s\'s email address. type !@continue to continue to select a message and send the email: ' % i)
                    if(newRecipient == '!@continue'):
                        repeat = False
                    else:
                        recipient.append(newRecipient)
                    i += 1

            message = input("enter the content of the email: ")
            print('Sending email...')
            if(not sendMultiple):
                sendFormattedEmail(password, recipient, subject, message)
            else:
                sendMultipleFormattedEmails(password, recipient, subject, message)
            print("Email sent!")
        else:
            wrongLineError()

    elif(command == "help"):
        if(sudoLn):
            print(username + """-sudo.ln command help:
    >>edit file anywhere > input(s): path > Takes a file path and edits that file.
    If the file doesn't already exist it is created.
    If you wish to edit a file in the same location as geeko simply enter the name and leave out   the path. 
    >>delete file anywhere > input(s): path > Takes a file path and deletes the file with that path.
    If you wish to delete a file in the same location as geeko simply enter the name and leave out the path.
    >>send unformatted email > input(s): recipient, message > Sends an email to the recipient containing the message you entered.
    >> send formatted email > input(s): recipient, subject line, message > Sends an email to the recipient with the entered subject line and message.
    This also enters To and From information into the email.
    >>help > no inputs > Shows this help message.
    A different message is shown for cmd.ln and sudo.ln.
    >>close > input(s): confirmation > If confirmed exits out of geeko.
    END %s-sudo.ln HELP""" % username)
        else:
            print(username + """-cmd.ln command help:
    >>add > input(s): first number, second number > Adds two numbers together.
    >>subtract > input(s): first number, second number > Subtracts the second number from the first number.
    >>multiply > input(s): first number, second number > Multiplies the two numbers together.
    >>divide > input(s): first number, second number > Divides the first number by the second number.
    >>area of rectangle > input(s): length, width > Calculates the area of a rectangle with the given length and width.
    >>area of triangle > input(s): length, height > Calculates the area of a triangle with the given length and height.
    >>area of circle > input(s): radius > Calculates the area of a triangle with the given radius.
    >>pi > no inputs > Prints the first 16 digits of pi
    >>welcome > no inputs > Gives you a special welcome.
    >>print reversed sentence > input(s): sentence > Prints the sentence backwards.
    >>help > no inputs > Shows this help message. 
    The help message is different in cmd.ln and sudo.ln.
    >>close > input(s): confirmation > If confirmed exits out of geeko.
    END %s-cmd.ln HELP""" % username )

    elif(command == 'print reversed sentence'):
        sentence = input("enter the senctence you want to reverse: ")
        sentence = sentence[::-1]
        print(sentence)

    elif(command == 'weather'):
        get_weather(loc_id)

    elif(command == "close"):
        confirmedOrDenied = False

        while(not confirmedOrDenied):
            confirmation = input("are you sure you want to close geeko [Y/N]: ")
            if(confirmation == 'y' or confirmation == 'Y'):
                exit()
            elif(confirmation == 'n' or confirmation == 'N'):
                confirmedOrDenied = True
                print("cancelled")
            else:
                print('invalid response please enter Y or N')
    else:
        print(command + ' is not a valid command make sure everything is spelled correctly') # if no registered command was entered return invalid command

【问题讨论】:

  • 对于当前的问题,这有点太多的代码,但有几种方法。我可能只是使用对http://wttr.in/?0 的请求来获取当前天气,但如果您想使用具有更多选项的 API,您可以使用 OpenWeatherMap 之类的东西:stackoverflow.com/questions/1474489/python-weather-api
  • 感谢您的建议!这是我的第一个 stackoverflow 问题,所以我不知道自己在做什么,哈哈。

标签: python


【解决方案1】:

有两种主要方法可以做到这一点。

第一个是webscrape,使用requests和beautifulsoup4。这可以通过 google 轻松完成,因为如果您搜索“天气 {city-name}”,它会为您提供那里的天气摘要。

第二种是使用openweathermap之类的api,上面有个很棒的geeksforgeeks tutorial

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-20
    • 1970-01-01
    • 1970-01-01
    • 2017-05-29
    • 2016-11-16
    • 2013-10-02
    • 1970-01-01
    相关资源
    最近更新 更多