Bitperi(Periklis Gkolias)

Productivity tips and coding for thriving people

A quick way to automate your conda uninstalls

It’s been a while since my last article, truth be told it was an over-demanding set of months for me and not only in my professional life. One of the best things though, I have done during this past period was to submit a chapter to First year in code (Thanks Isaac for the opportunity :) )

Today, I am gonna showcase a python script I made, to help you uninstall all the anaconda packages that match a certain filter.

Here is the whole script. Nothing much, nothing worth a Turing award, just thought it would be useful to someone.

import os

# Example function, not uninstall packages with the 
# digram py in their name. Please update accordingly
def filter_function(name):
    return 'py' not in name

# Get the installed conda packages
conda_list_output = os.popen('conda list').read()

# Put them in a list
output_in_lines = conda_list_output.split('\n')

# Line 4 and onwards is what we want (feel free to examine it)
output_in_lines = output_in_lines[3:]

# Name appears in the beginning of the line
only_names = [line.strip().split(' ')[0] for line in output_in_lines]

# Apply the filter defined above
filtered_list = list(filter(filter_function, only_names))

# Convert the list of uninstall candidates to a string
# and run the unins
cmd = f'conda uninstall {" ".join(filtered_list)}'

os.system(cmd)

There is extensive logging in the file but if you are a TL;DR guy

  • We get the list of packages
  • We clean it and convert it to a friendly format
  • We filter out the unwanted ones
  • We build and run the uninstall command

The only thing you need to change is the filter function, you can make the filter as sophisticated as it gets

Thank you for reading this really short article. Let me know if this was helpful. :)

comments powered by Disqus