Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
loop running indefinitely
#1
My elif command is running indefinitely. My elif logic is simple. I have two API. 1) USA API- I wanted this API need should work only before year 1985. 2) Australia API- This API works only for year 1985 & after. After that I merge these two dataframe into one dataframe.

To run this logic we need to write this command in the terminal. You can put any value of longitude, latitude in below command.

python test.py -latitude '88' -longitude '75' -startYear '1975' -endYear '2021

File attached.

Can anyone one help me out why this elif logic is running indefinitely??? Also, please tell me how to fixed it.

import requests
import json
import argparse
import time
import pandas as pd
import warnings
warnings.filterwarnings("ignore")
##
#   sample command: python test.py -latitude '' -longitude '' -startYear '' -endYear ''
##
parser = argparse.ArgumentParser(description="Process some integers.")
parser.add_argument("-latitude", help="Latitude(Degress)")
parser.add_argument("-longitude", help="Longitude(Degress)")
parser.add_argument("-startYear", help="Start of the Year")
parser.add_argument("-endYear", help="End of the Year")
parser.add_argument("--verbose", help="display processing information")
start = time.time()
def main(latitude,longitude,startYear,endYear,verbose):   
    parameters = {  #Australia API
        "latd": latitude, # [deg]
        "latm": 00, # [deg]
        "lats": 00, # [deg]
        "lond": longitude, # [deg]
        "lonm": 00, # [deg]
        "lons": 00, # [deg]
        "elev" : 00, # [km]
        "year" : None, # [YYYY]
        "month" : '07', # [MM]
        "day": '01', # [DD]
        "Ein": 'D'  # [Model]
    }
    parameters1 = {    #USA API
    'lat1': latitude, # [deg]
    'lon1': longitude, # [deg]
    'model': 'IGRF', # [Model]
    'startYear': None, # [year]
    'startMonth': 7, # [month]
    'startDay':1,  # [date] 
    'resultFormat': 'json', # [format] 
}
    hostname = "https://api.geomagnetism.ga.gov.au/agrf" #Australia API
    hostname1 = "http://www.ngdc.noaa.gov/geomag-web/calculators/calculateDeclination?%s"  #USA API
    df_1=pd.DataFrame()
    df_2=pd.DataFrame()
    for year in range(startYear, endYear): 
        if endYear < 1985:
            if  startYear < 1985:        
                print('Good, this loop working')        
        elif startYear < 1985:  # Loop is running indefinetly
            for year in range(startYear, 1985): #USA API
                try:
                    parameters1["year"] = year      #USA API
                    response = requests.get(hostname1, params= dict(parameters1, ps=str(year)))
                    # extract JSON payload of response as Python dictionary
                    json_payload = response.json()
                    # raise an Exception if we encoutnered any HTTP error codes like 404
                    response.raise_for_status()
                except requests.exceptions.ConnectionError as e:
                    # handle any typo errors in url or endpoint, or just patchy internet connection
                    print(e)
                except requests.exceptions.HTTPError as e:
                    # handle HTTP error codes in the response
                    print(e, json_payload['error'])
                except requests.exceptions.RequestException as e:
                    # general error handling
                    print(e, json_payload['error'])
                else:
                    json_payload = response.json()
                    #print(json.dumps(json_payload, indent=4, sort_keys=True))
                    df = pd.DataFrame(json_payload['result'])
                    new_row = {
                        "SourceFile": hostname1,
                        "Year": year,
                        "Magnetic Declination": df.iloc[0, 2],
                        "Latitude": -35,
                        "Longitude": 145
                    }
                    df_1 = df_1.append(new_row, ignore_index=True)
                    df_1 = df_1[['Year', 'Latitude', 'Longitude','Magnetic Declination','SourceFile']]
                    df_1.to_csv('magnetic_declination_usa.csv',index=False)  

                    for year in range(1985, endYear):
                        try:     #Australia API
                            parameters["year"] = year
                            response = requests.get(hostname, params= dict(parameters, ps=str(year)))
                            # extract JSON payload of response as Python dictionary
                            json_payload = response.json()
                            # raise an Exception if we encoutnered any HTTP error codes like 404
                            response.raise_for_status()
                        except requests.exceptions.ConnectionError as e:
                            # handle any typo errors in url or endpoint, or just patchy internet connection
                            print(e)
                        except requests.exceptions.HTTPError as e:
                            # handle HTTP error codes in the response
                            print(e, json_payload['error'])
                        except requests.exceptions.RequestException as e:
                            # general error handling
                            print(e, json_payload['error'])
                        else:
                            json_payload = response.json()
                            #print(json.dumps(json_payload, indent=4, sort_keys=True))
                            df = pd.DataFrame(json_payload)
                            new_row = {
                                "SourceFile": hostname,
                                "Year": year,
                                "Magnetic Declination": df.iloc[5, 3],
                                "Latitude": latitude,
                                "Longitude": longitude
                            }
                            df_2 = df_2.append(new_row, ignore_index=True)
                            df_2 = df_2[['Year', 'Latitude', 'Longitude','Magnetic Declination','SourceFile']]
                            df_2["Magnetic Declination"] = df_2["Magnetic Declination"].apply(lambda x: x.replace(" deg", ""))
                            df_2.to_csv('magnetic_declination_australia.csv',index=False)

                df_3 = pd.concat([df_1,df_2], axis=0)            #Merge dataframe into one    
                df_3.to_csv('Magnetic_Declination_(USA+Australia).csv',index=False) 

        else:    # Case where endYear < 1985 and startYear > 1985 (probably an input error)
            print("Invalid Year. Please check the startYear & EndYear.")
                                               
if __name__ == '__main__':
    start = time.time()
    args = parser.parse_args()
    latitude = args.latitude
    longitude = args.longitude
    startYear = int(args.startYear)
    endYear = int(args.endYear)
    verbose = args.verbose
    main(latitude,longitude,startYear,endYear,verbose)  # Calling Main Function
    print("Processed time:", time.time() - start)  # Total Time

Attached Files

.py   check.py (Size: 6.7 KB / Downloads: 235)
Reply


Messages In This Thread
loop running indefinitely - by shantanu97 - Jun-14-2021, 12:10 PM
RE: loop running indefinitely - by snippsat - Jun-14-2021, 12:55 PM
RE: loop running indefinitely - by deanhystad - Jun-14-2021, 02:06 PM
RE: loop running indefinitely - by Gribouillis - Jun-14-2021, 03:38 PM
RE: loop running indefinitely - by deanhystad - Jun-14-2021, 04:52 PM
RE: loop running indefinitely - by Underscore - Sep-29-2021, 05:58 PM
RE: loop running indefinitely - by deanhystad - Sep-29-2021, 08:03 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  help RuntimeError: no running event loop marpaslight 5 4,172 Oct-18-2022, 10:04 PM
Last Post: marpaslight
  bleak library RuntimeError: This event loop is already running alice93 3 4,364 Sep-30-2021, 08:06 AM
Last Post: alice93
  Running A Loop Until You See A Particular Result knight2000 6 32,198 Sep-04-2021, 08:55 AM
Last Post: knight2000
  Running loop at specific frequency mdsousa 3 6,229 Apr-21-2021, 11:22 AM
Last Post: jefsummers
  RuntimeError: This event loop is already running newbie2019 2 7,107 Sep-30-2020, 06:59 PM
Last Post: forest44
  Running function from parent module which has a loop in it. ta2909i 1 2,814 Nov-18-2019, 07:04 PM
Last Post: Gribouillis
  How to add coroutine to a running event loop? AlekseyPython 1 8,391 Mar-21-2019, 06:04 PM
Last Post: nilamo
  action on MQTT while long loop is running runboy 4 6,298 Oct-05-2018, 11:57 PM
Last Post: runboy
  Outer loop not running ted_gress 2 3,430 Aug-25-2018, 07:56 AM
Last Post: volcano63
  Running Class methods in a loop and updating variables. ujjwalrathod007 3 6,631 Oct-05-2016, 07:11 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

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