1

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
...
General Grievance
  • 4,555
  • 31
  • 31
  • 45
  • ```os.system('pip list')``` does not work because it lists packages in the "global env" not the virtual env – Ahadu Tsegaye Abebe Oct 02 '20 at 12:30
  • @jabberwocky had already answered to a similar question. This solution works fine for me. `import pkg_resources` `installed_packages = {d.project_name: d.version for d in pkg_resources.working_set}` – Ahadu Tsegaye Abebe Oct 02 '20 at 12:45

1 Answers1

1

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

Md Johirul Islam
  • 5,042
  • 4
  • 23
  • 56