Last active
June 23, 2024 23:13
-
-
Save DanishjeetSingh/3209e462785b528dc182c4b49428628a to your computer and use it in GitHub Desktop.
Python utility for managing Conda environments and configuration files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import sys | |
import configparser | |
def _get_conda_env(): | |
"""Return the path of the current Conda environment if it exists, otherwise raise an error.""" | |
conda_env_path = os.getenv('CONDA_PREFIX') | |
if conda_env_path is None: | |
raise OSError("Please use a Conda environment") | |
return conda_env_path | |
def _get_home_dir(conda_env_name='miniconda3'): | |
"""Determine the HOME_DIR based on the specific Conda environment or raise an error.""" | |
try: | |
conda_env_path = _get_conda_env() | |
if os.path.basename(conda_env_path) == conda_env_name: | |
home_dir = os.getenv('HOME_DIR') | |
if home_dir is None: | |
raise EnvironmentError("HOME_DIR environment variable is not set") | |
return home_dir | |
else: | |
raise EnvironmentError(f"Wrong Conda environment: {conda_env_path}") | |
except Exception as e: | |
print(f"Error: {e}", file=sys.stderr) | |
def jhd(*paths): | |
""" | |
Joins the home directory with the specified paths. | |
:param paths: Paths to join with the home directory | |
:return: The joined path | |
""" | |
home_dir = _get_home_dir() | |
# assumes each path is relative, hence the preprocessing | |
relative_paths = [path.lstrip('/') for path in paths] | |
return os.path.join(home_dir, *relative_paths) | |
config = configparser.ConfigParser() | |
config.read(jhd('config.ini')) | |
# global variables | |
HOME_DIR=_get_home_dir() | |
PERSPECTIVE_API_KEY=config['PERSPECTIVE']['api_key'] | |
APIFY_API_KEY=config['APIFY']['api_key'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I use this file for any python projects I take on
jhd(file_path)
and everything works smoothlyFeel free to add more to it
The error handling might be a little bloated, but if it works it works!