Python3: list all installed packages and versions in a virtual environment programmatically

1.3k views Asked by At

I'm using pipenv to create a virtual environment and I'm writing write a script that fetches all the installed packages and puts in a dictionary their names and versions, just as pip list would do if called from within the virutualenv:

> C:\Users\my_project > pipenv shell
>(.venv) C:\Users\my_project > pip list
Package         Version
--------------- ---------
argcomplete     0.8.1
bottle          0.12.4
certifi         2020.6.20
colorama        0.4.3
cx-Oracle       7.3.0
cycler          0.10.0
...
1

There are 1 answers

0
Md Johirul Islam On

Something like following can be used

import subprocess
out = subprocess.Popen(['pip', 'list'],
           stdout=subprocess.PIPE,
           stderr=subprocess.STDOUT)
stdout,stderr = out.communicate()

print(stdout)

You can then parse the stdout in your desired format