Python Forum

Full Version: Why is this Python code running twice?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi everybody
Why is this code running twice? Is this related with the variables that the code imports from convert_nc_to_csv1?
Thank you.


# Reading the netcdf file
from netCDF4 import Dataset
import numpy as np
import pandas as pd
from convert_nc_to_csv1 import lat_of_station, lon_of_station

data = Dataset (r'G:\My Drive\Python_Projects\NC4 Files code\ERA5-Land hourly data from 1950 to present\ERA5_land_hourly_data_from_2000_to_2010.nc')

data_range = pd.date_range(start = '2000-01-01', end = '2011-01-01', freq='H')

lat = data.variables['latitude'][:]
lon = data.variables['longitude'][:]

sq_diff_lat = (lat - lat_of_station)**2
sq_diff_lon = (lon - lon_of_station)**2

#Identifying the index of the minimum value for lat and lon
min_index_lat = sq_diff_lat.argmin()
min_index_lon = sq_diff_lon.argmin()


df1 = pd.DataFrame(0, columns = ['t2m'], index = data_range)
df = df1.iloc[:-1 , :]
dt = np.arange(0, data.variables['time'].size)

temperature = data.variables['t2m']

for time_index in dt:
    df.iloc[time_index] = temperature[time_index, min_index_lat,min_index_lon]-273.15
    print (time_index)

#Saving the time series to csv
df.to_csv('64_PONTE MESTRAS_3.csv')
what is convert_nc_to_csv1 and what is its content?
And how do you know it runs twice?
Importing a module may execute code in that module, but this only happens once, not twice. What is your evidence that your code runs twice? Be specific.
(Jan-31-2022, 03:34 PM)buran Wrote: [ -> ]what is convert_nc_to_csv1 and what is its content?
And how do you know it runs twice?

Hi convert_nc_to_csv1 is another .py file with the value of those two variables: lat_of_station and lon_of_station.
I know it runs twice because I can see the time index value inside the loop in the spyder console running from 1 to 90000 and the returning to 1 and running again until it stops in 90000.
dt should not have a repeat, but I like to be sure. I would print something at the start of the script (print("Hi Mom")). If you see that twice it would mean the script is running twice. If that happens try running the script from the command line instead of spyder.
(Jan-31-2022, 08:05 PM)deanhystad Wrote: [ -> ]dt should not have a repeat, but I like to be sure. I would print something at the start of the script (print("Hi Mom")). If you see that twice it would mean the script is running twice. If that happens try running the script from the command line instead of spyder.

Hi it only prints (Hi Mom) :) once. But something strange is happening. I have delete this line:

print (time_index)
However in the console I can still see the output of time index once (from 1 to 90000). So I see "Hi Mom" and the output of time index once (from 1 to 90000). This is very strange.

I will let it stay like this....
Thank you for you help