How to Use Pip Programmatically in Docker for Installing the ‘debugpy’ Module

  • A simple form is to begin the module with
import subprocess
import sys
def install(package):
subprocess.check_call([sys.executable, "-m", "pip", "install", package])
  • You, however, may want first want to check if the module has not already been installed
  • …and install it only as a way of handling the ModuleNotFoundError and proceeding further
import subprocess
import sys
try:
import debugpy
except ModuleNotFoundError:
subprocess.check_call([sys.executable, "-m", "pip", "install", "debugpy"])
import debugpy
debugpy.listen(("0.0.0.0", 5678))
print("Waiting for client to attach...")
debugpy.wait_for_client()
print("hello")
  • Once I run the python script in a fresh container, I get the following output
Collecting debugpy

Downloading debugpy-1.5.1-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl (1.9 MB)

|█████████████████████████████▎ | 1.7 MB 1.3 MB/s eta 0:00:01

|████████████████████████████████| 1.9 MB 1.3 MB/s

Installing collected packages: debugpy

Successfully installed debugpy-1.5.1

WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv

Waiting for client to attach...
  • … happy debugging !

LINKS

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Pavol Kutaj

Pavol Kutaj

63 Followers

Infrastructure Support Engineer/Technical Writer (snowplow.io) with a passion for Python/writing documentation. More about me: https://pavol.kutaj.com