Skip to content

Instantly share code, notes, and snippets.

@DanishjeetSingh
Last active June 23, 2024 23:13
Show Gist options
  • Save DanishjeetSingh/3209e462785b528dc182c4b49428628a to your computer and use it in GitHub Desktop.
Save DanishjeetSingh/3209e462785b528dc182c4b49428628a to your computer and use it in GitHub Desktop.
Python utility for managing Conda environments and configuration files
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']
@DanishjeetSingh
Copy link
Author

DanishjeetSingh commented Jun 16, 2024

I use this file for any python projects I take on

  • fixes relative import issues, just do jhd(file_path) and everything works smoothly
  • also helps with managing api key imports

Feel free to add more to it

The error handling might be a little bloated, but if it works it works!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment