1
1
# -*- coding: utf-8 -*-
2
- ##
3
- ## helper_functions.py
4
- ## spt_compute
5
- ##
6
- ## Created by Alan D. Snow.
7
- ## Copyright © 2015-2016 Alan D Snow. All rights reserved.
8
- ## License: BSD-3 Clause
2
+ #
3
+ # helper_functions.py
4
+ # spt_ecmwf_autorapid_process
5
+ #
6
+ # Created by Alan D. Snow
7
+ # License: BSD-3 Clause
9
8
10
9
import datetime
11
10
from glob import glob
12
- from netCDF4 import Dataset , num2date # http://unidata.github.io/netcdf4-python/
13
11
import os
14
12
import re
15
13
from shutil import rmtree
16
14
import sys
17
15
18
16
19
- #----------------------------------------------------------------------------------------
17
+ # ----------------------------------------------------------------------------------------
20
18
# HELPER FUNCTIONS
21
- #----------------------------------------------------------------------------------------
19
+ # ----------------------------------------------------------------------------------------
22
20
class CaptureStdOutToLog (object ):
23
- def __init__ (self , out_file_path ):
24
- self .out_file_path = out_file_path
21
+ def __init__ (self , log_file_path , error_file_path = None ):
22
+ self .log_file_path = log_file_path
23
+ self .error_file_path = error_file_path
24
+ if error_file_path is None :
25
+ self .error_file_path = "{0}.err" .format (os .path .splitext (log_file_path )[0 ])
26
+
25
27
def __enter__ (self ):
26
28
self ._stdout = sys .stdout
27
29
self ._stderr = sys .stderr
28
- sys .stdout = sys .stderr = open (self .out_file_path , 'w' )
30
+ sys .stdout = open (self .log_file_path , 'w' )
31
+ sys .stderr = open (self .error_file_path , 'w' )
29
32
return self
33
+
30
34
def __exit__ (self , * args ):
31
35
sys .stdout .close ()
32
36
sys .stdout = self ._stdout
@@ -46,43 +50,44 @@ def case_insensitive_file_search(directory, pattern):
46
50
raise
47
51
48
52
49
- def clean_main_logs (main_log_directory , prepend = "spt_compute_ecmwf_" ,
50
- lock_file_name = "spt_compute_ecmwf_run_info_lock.txt" ,
51
- log_file_path = "" ):
53
+ def clean_main_logs (main_log_directory , prepend = "rapid_" , log_file_path = "" ):
52
54
"""
53
- Removes old log files older than one week old in main log directory
55
+ This removes main logs older than three days old
54
56
"""
55
57
date_today = datetime .datetime .utcnow ()
56
- week_timedelta = datetime .timedelta (7 )
58
+ week_timedelta = datetime .timedelta (3 )
59
+
60
+ # clean up log files
57
61
main_log_files = [f for f in os .listdir (main_log_directory ) if
58
62
not os .path .isdir (os .path .join (main_log_directory , f ))
59
63
and not log_file_path .endswith (f )
60
- and f != lock_file_name ]
64
+ and ( f . endswith ( 'log' ) or f . endswith ( 'err' )) ]
61
65
62
66
for main_log_file in main_log_files :
63
67
try :
64
- log_datetime = datetime .datetime .strptime (main_log_file , "{0}%y%m%d%H%M%S.log" .format (prepend ))
65
- if (date_today - log_datetime > week_timedelta ):
68
+ log_datetime = datetime .datetime .strptime (main_log_file [:18 ],
69
+ "{0}%y%m%d%H%M%S" .format (
70
+ prepend ))
71
+ if date_today - log_datetime > week_timedelta :
66
72
os .remove (os .path .join (main_log_directory , main_log_file ))
67
73
except Exception as ex :
68
74
print (ex )
69
75
pass
70
76
71
77
72
- def clean_logs (condor_log_directory , main_log_directory , prepend = "spt_compute_ecmwf_ " , log_file_path = "" ):
78
+ def clean_logs (condor_log_directory , main_log_directory , prepend = "rapid_ " , log_file_path = "" ):
73
79
"""
74
- This removed logs older than one week old
80
+ This removes all logs older than three days old
75
81
"""
76
82
date_today = datetime .datetime .utcnow ()
77
- week_timedelta = datetime .timedelta (7 )
78
- #clean up condor logs
83
+ week_timedelta = datetime .timedelta (3 )
84
+ # clean up condor logs
79
85
condor_dirs = [d for d in os .listdir (condor_log_directory ) if
80
86
os .path .isdir (os .path .join (condor_log_directory , d ))]
81
-
82
87
for condor_dir in condor_dirs :
83
88
try :
84
89
dir_datetime = datetime .datetime .strptime (condor_dir [:11 ], "%Y%m%d.%H" )
85
- if ( date_today - dir_datetime > week_timedelta ) :
90
+ if date_today - dir_datetime > week_timedelta :
86
91
rmtree (os .path .join (condor_log_directory , condor_dir ))
87
92
except Exception as ex :
88
93
print (ex )
@@ -96,10 +101,11 @@ def find_current_rapid_output(forecast_directory, watershed, subbasin):
96
101
Finds the most current files output from RAPID
97
102
"""
98
103
if os .path .exists (forecast_directory ):
99
- basin_files = glob (os .path .join (forecast_directory ,"Qout_%s_%s_*.nc" % (watershed , subbasin )))
100
- if len (basin_files ) > 0 :
104
+ basin_files = glob (os .path .join (forecast_directory ,
105
+ "Qout_{0}_{1}_*.nc" .format (watershed , subbasin )))
106
+ if len (basin_files ) > 0 :
101
107
return basin_files
102
- #there are none found
108
+ # there are none found
103
109
return None
104
110
105
111
@@ -110,7 +116,7 @@ def get_valid_watershed_list(input_directory):
110
116
valid_input_directories = []
111
117
for directory in os .listdir (input_directory ):
112
118
if os .path .isdir (os .path .join (input_directory , directory )) \
113
- and len (directory .split ("-" )) == 2 :
119
+ and len (directory .split ("-" )) == 2 :
114
120
valid_input_directories .append (directory )
115
121
else :
116
122
print ("{0} incorrectly formatted. Skipping ..." .format (directory ))
@@ -121,8 +127,8 @@ def get_date_timestep_from_forecast_folder(forecast_folder):
121
127
"""
122
128
Gets the datetimestep from forecast
123
129
"""
124
- #OLD: Runoff.20151112.00.netcdf.tar.gz
125
- #NEW: Runoff.20160209.0.exp69.Fgrid.netcdf.tar
130
+ # OLD: Runoff.20151112.00.netcdf.tar.gz
131
+ # NEW: Runoff.20160209.0.exp69.Fgrid.netcdf.tar
126
132
forecast_split = os .path .basename (forecast_folder ).split ("." )
127
133
forecast_date_timestep = "." .join (forecast_split [1 :3 ])
128
134
return re .sub ("[^\d.]+" , "" , forecast_date_timestep )
@@ -142,16 +148,14 @@ def get_datetime_from_forecast_folder(forecast_folder):
142
148
:param forecast_folder:
143
149
:return:
144
150
"""
145
- return get_datetime_from_date_timestep (
146
- get_date_timestep_from_forecast_folder (forecast_folder ))
147
-
151
+ return get_datetime_from_date_timestep (get_date_timestep_from_forecast_folder (forecast_folder ))
148
152
149
153
def get_ensemble_number_from_forecast (forecast_name ):
150
154
"""
151
155
Gets the datetimestep from forecast
152
156
"""
153
- #OLD: 20151112.00.1.205.runoff.grib.runoff.netcdf
154
- #NEW: 52.Runoff.nc
157
+ # OLD: 20151112.00.1.205.runoff.grib.runoff.netcdf
158
+ # NEW: 52.Runoff.nc
155
159
forecast_split = os .path .basename (forecast_name ).split ("." )
156
160
if forecast_name .endswith (".205.runoff.grib.runoff.netcdf" ):
157
161
ensemble_number = int (forecast_split [2 ])
@@ -183,4 +187,4 @@ def log(message, severity):
183
187
if severity in print_me :
184
188
print ("{0} {1}" .format (severity , message ))
185
189
else :
186
- raise Exception (message )
190
+ raise Exception (message )
0 commit comments