DEV Community

Anurag Pandey
Anurag Pandey

Posted on

Copy venv from one folder to another and still be able to use it?

If you have ever copied the python virtual environment folder from one location to another and faced problem using it, this article will help you understand how you can solve this problem.

Let us first create a folder, named example and then create a virtual environment and install flask using pip

$ mkdir example
$ cd example
$ python -m venv venv
$ source venv/bin/activate
$ pip install Flask
Enter fullscreen mode Exit fullscreen mode

Now you have a virtual env with flask installed.

After doing this python sets an environment variable VIRTUAL_ENV, let us check its value.

$ echo $VIRTUAL_ENV
/home/username/example/venv
Enter fullscreen mode Exit fullscreen mode

We will now move this venv folder to some other folder.

$ mkdir example2
$ mv venv/ example2/
$ cd example2
$ source venv/bin/activate
Enter fullscreen mode Exit fullscreen mode

Now let us check the value of VIRTUAL_ENV variable

$ echo $VIRTUAL_ENV
/home/username/example/venv
Enter fullscreen mode Exit fullscreen mode

Wow, this is strange. I have moved the folder but still the value of VIRTUAL_ENV variable is the same?
This is because when you create the virtual environment, the location is hardcoded based on current directory.
You can check this inside activate file we have previously used to activate the virtual environment.
You will find something like VIRTUAL_ENV='/home/username/example/venv'.

The solution for using the virtual environment at the new location is simple. Just change this path in all program inside venv/bin directory to the new path :-)
Please don't do it manually!!!
Use tools like sed on unix or similar tools for the same.

Example using sed:

$ old_path='/home/username/example/venv'
$ new_path='/home/username/example/example2/venv'
$ cd venv/bin/
$ sed -i "s|$old_path|$new_path|g" *
Enter fullscreen mode Exit fullscreen mode

The last command is replace in-place the value of old_path with new_path. * signifies all files in current directory(not exactly, but for this example consider it). Make sure you run this command while present in venv/bin folder.

After doing this reactivate the virtual env.

$ source venv/bin/activate
Enter fullscreen mode Exit fullscreen mode

And voila!

Reference:

  1. For sed command used: https://stackoverflow.com/questions/10309968/sed-search-and-replace-strings-containing

Discussion (0)