1 # Copyright (c) 2016 Cable Television Laboratories, Inc. ("CableLabs")
2 # and others. All rights reserved.
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at:
8 # http://www.apache.org/licenses/LICENSE-2.0
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
21 __author__ = 'spisarski'
24 Utilities for basic file handling
27 logger = logging.getLogger('file_utils')
30 def file_exists(file_path):
32 Returns True if the image file already exists and throws an exception if the path is a directory
35 if os.path.exists(file_path):
36 if os.path.isdir(file_path):
38 return os.path.isfile(file_path)
42 def get_file(file_path):
44 Returns True if the image file has already been downloaded
45 :return: the image file object
46 :raise Exception when file cannot be found
48 if file_exists(file_path):
49 return open(file_path, 'r')
51 raise Exception('File with path cannot be found - ' + file_path)
54 def download(url, dest_path):
56 Download a file to a destination path given a URL
59 name = url.rsplit('/')[-1]
60 dest = dest_path + '/' + name
62 # Override proxy settings to use localhost to download file
63 proxy_handler = urllib2.ProxyHandler({})
64 opener = urllib2.build_opener(proxy_handler)
65 urllib2.install_opener(opener)
66 response = urllib2.urlopen(url)
67 except (urllib2.HTTPError, urllib2.URLError):
70 with open(dest, 'wb') as f:
71 f.write(response.read())
75 def read_yaml(config_file_path):
77 Reads the yaml file and returns a dictionary object representation
78 :param config_file_path: The file path to config
81 logger.debug('Attempting to load configuration file - ' + config_file_path)
82 with open(config_file_path) as config_file:
83 config = yaml.safe_load(config_file)
84 logger.info('Loaded configuration')
86 logger.info('Closing configuration file')
90 def read_os_env_file(os_env_filename):
92 Reads the OS environment source file and returns a map of each key/value
93 Will ignore lines beginning with a '#' and will replace any single or double quotes contained within the value
94 :param os_env_filename: The name of the OS environment file to read
98 logger.info('Attempting to read OS environment file - ' + os_env_filename)
100 for line in open(os_env_filename):
102 if not line.startswith('#') and line.startswith('export '):
103 line = line.lstrip('export ').strip()
104 tokens = line.split('=')
106 # Remove leading and trailing ' & " characters from value
107 out[tokens[0]] = tokens[1].lstrip('\'').lstrip('\"').rstrip('\'').rstrip('\"')