Select Git revision
common_radiohdl.py
-
Pieter Donker authoredPieter Donker authored
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
common_radiohdl.py 2.58 KiB
import os
import inspect
def listify(obj):
"""
Can be used to force method input to a list.
"""
if isinstance(obj, list):
return obj
else:
return [obj]
# try:
# return list(obj)
# except TypeError:
# return [obj]
def unlistify(obj):
"""
Converts 1-element list to x.
"""
# The isinstance() built-in function is recommended over the type()
# built-in function for testing the type of an object
if isinstance(obj, list):
if len(obj) == 1:
return obj[0]
return obj
def remove_from_list_string(list_str, item_str, sep=' '):
"""Treat the string list_str as a list of items that are separated by sep and then
remove the specified item_str string from the list and return the list as a
string of items separated by sep. Also remove any duplicate items.
"""
_list_str = list_str.split(sep)
_list_str = unique(_list_str)
_list_str.remove(item_str)
return sep.join(_list_str)
def unique(in_list):
"""
Extract unique list elements (without changing the order like set() does)
"""
result = []
for item in in_list:
if item in result:
continue
result.append(item)
return result
def method_name(caller_depth=0):
"""
Returns the name of the caller method.
"""
# Note: inspect.stack()[0][3] would return the name of this method.
return inspect.stack()[caller_depth+1][3]
def mkdir(path):
"""Recursively create leave directory and intermediate directories if they do not already exist."""
expand_path = os.path.expandvars(path) # support using environment variables in the file path
expand_path = os.path.expanduser(expand_path) # support using ~ in the file path
if not os.path.exists(expand_path):
os.makedirs(expand_path)
def expand_file_path_name(fpn, dir_path=''):
""" Expand environment variables in fpn to get file_path_name.
- if it is an absolute path return file_path_name else
- if it still has a local file path prepend dir_path to the file_path_name and return dir_path + file_path_name.
"""
file_path_name = os.path.expandvars(fpn) # support using environment variables in the file path
file_path_name = os.path.expanduser(file_path_name) # support using ~ in the file path
if os.path.isabs(file_path_name):
return file_path_name # use absolute path to file
# derive path to file from the directory path and a directory path to the file
return os.path.join(os.path.expandvars(dir_path), file_path_name)