Skip to content

Instantly share code, notes, and snippets.

@robinkaty
Created August 7, 2023 04:51
Show Gist options
  • Save robinkaty/06f8d60808a62b1ba97d52fea3257838 to your computer and use it in GitHub Desktop.
Save robinkaty/06f8d60808a62b1ba97d52fea3257838 to your computer and use it in GitHub Desktop.
Edit PATH Variable Strings or help find duplicates in path
import os
import tempfile
import subprocess
def edit_path_variable():
# Get the current PATH variable
current_path = os.environ.get('PATH', '')
paths_list = current_path.split(':')
# Display the current paths to the user
print("Current PATH:")
for idx, path in enumerate(paths_list, start=1):
print(f"{idx}. {path}")
# Prepare the text to be edited with "*" before duplicate paths
edited_text = "\n".join(f"*{path}" if paths_list.count(path) > 1 else path for path in paths_list)
# Create a temporary file and write the paths into it
with tempfile.NamedTemporaryFile(mode='w', delete=False) as temp_file:
temp_file.write(edited_text)
# Open the temporary file with the default text editor
try:
subprocess.run([os.environ.get('EDITOR', 'vi'), temp_file.name], check=True)
except subprocess.CalledProcessError:
print("Error: Could not open the editor. Please check your default text editor.")
# Read the edited paths from the temporary file
edited_paths = []
with open(temp_file.name, 'r') as edited_file:
edited_paths = edited_file.read().splitlines()
# Remove "*" prefix before saving the edited paths
updated_paths = [path.lstrip("*") for path in edited_paths]
# Join the edited paths back into a new PATH variable
new_path = ":".join(updated_paths)
# Update the PATH environment variable
os.environ['PATH'] = new_path
# Display the updated PATH with "*" for duplicates
print("\nUpdated PATH:")
for idx, path in enumerate(updated_paths, start=1):
print(f"{idx}. {path}")
# Clean up the temporary file
os.remove(temp_file.name)
if __name__ == "__main__":
edit_path_variable()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment