Automating Virtual Environment Setup in Python

Home > Routine

Objective: automate the setup of a program that uses virtual environment and external libraries. This is for Windows system.

This month I was working on a program that uses virtual environment, some python packages with some tedious configuration settings. I figure it is best to automate python package installations and the configuration settings. Here, I demonstrate the part on python package installations.

We start by creating a virtual environment using  virtualenv. First, create the folder Desktop/adhoc. Run the command line then

cd C:\Users\etjoa003\Desktop\adhoc # adjust your path accordingly
:: pip install virtualenv :: uncomment this if you have not installed virtualenv
virtualenv testfolder
cd testfolder
Scripts\activate

If it works, see that we are in (testfolder) environment. Let us exit from it.

deactivate

Create the batch file and python script in adhoc folder.

setup_program.bat

@echo off
call to_install.py
pause

to_install.py

import os

bat = open("to_install.bat","w")
bat.write("@echo off\n")
bat.write("call cd C:\\Users\\etjoa003\\Desktop\\adhoc\\testfolder"+"\n")
bat.write("call Scripts\\activate"+"\n")
bat.write("call pip install numpy"+"\n")
bat.write("call pip install kero"+"\n")
bat.write("call pip freeze"+"\n")
bat.close()
os.system("to_install.bat")

pip freeze is just to list out all installed packages. You can also replace call pip install kero with call pip install –ignore-installed kero in case there is some trouble with the package (that is somehow installed but faulty) that gets in the way of new, fresh installation.

To proceed with the installation, double-click setup_program.bat.

Now let us see that kero and numpy is installed. In the command line,

cd C:\Users\etjoa003\Desktop\adhoc\testfolder
Scripts\activate
python
>>> import kero # if it is fine, no error will be raised
>>> import numpy

To uninstall, simply replace accordingly:

remove.bat

@echo off
call to_uninstall.py
pause

to_uninstall.py

import os

bat = open("to_uninstall.bat","w")
bat.write("@echo off\n")
bat.write("call cd C:\\Users\\etjoa003\\Desktop\\adhoc\\testfolder"+"\n")
bat.write("call Scripts\\activate"+"\n")
bat.write("call pip uninstall --yes numpy"+"\n")
bat.write("call pip uninstall --yes kero"+"\n")
bat.write("call pip freeze"+"\n")
bat.close()
os.system("to_uninstall.bat")