Hackernoon logoHow I accidentally deleted all my Python modules and got it back in 20 minutes by@balazs.saros

How I accidentally deleted all my Python modules and got it back in 20 minutes

Balazs Saros Hacker Noon profile picture

@balazs.sarosBalazs Saros

Frontend Developer

Today I was careless and it made me some trouble. I was working on a Flask web app and wasn’t using virtualenv due to my laziness. I just wanted a prototype up-and-running ASAP on Heroku. In order to deploy your app to Heroku you have to put a requirements.txt in the app’s directory. Without a virtualenv

pip freeze > requirements.txt

doesn’t work because it puts all globally installed modules into it. After 40 seconds of searching for solutions in Google I found pip-tools which claimed to help me out. After downloading it I took a quick look at the README for usage info but I wasn’t just careless that time, I was stupid as well because it clearly stated that

“Now that you have a requirements.txt, you can use pip-sync to update your virtual env to reflect exactly what’s in there. Note: this will install/upgrade/uninstall everything necessary to match the requirements.txt contents.”

I didn’t pay enough attention and ran pip-sync. And because the lack of virtualenv it synced my requirements.txt (with only 3 packages in it) with my globally installed Python modules. Yes, it uninstalled everything. All I had was this log in my terminal:

I felt angry about my mistake but I needed a solution. After a bunch of Google search I found out that no one have ever been that dumb to delete all their Python modules accidentally so I had to come up with something by myself and here is what I did:

  • copied the log from my terminal and pasted it in a python script as a multi line string
  • used vim search and replace to remove all the redundant info from the log
  • split the newly created string(with only the module names)
  • wrote a for loop over the list and ran the following line:
subprocess.call(‘sudo pip install %s’ % package_name, shell True)

It almost worked! The only problem was pip needed some packages preinstalled like appdirs, packaging and pyparsing. After installing those from my distro’s repository my scripted worked as expected and installed back everything.

The moral of the story:

  • don’t be stupid (always use virtualenv)
  • if you are stupid maybe you can compensate it with a clever idea
Hacker Noon is how hackers start their afternoons. We’re a part of the @AMIfamily. We are now accepting submissions and happy to discuss advertising &sponsorship opportunities.
To learn more, read our about page, like/message us on Facebook, or simply, tweet/DM @HackerNoon.
If you enjoyed this story, we recommend reading our latest tech stories and trending tech stories. Until next time, don’t take the realities of the world for granted!


Join Hacker Noon

Create your free account to unlock your custom reading experience.