Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run pdb inside a Docker Container

Tags:

python

docker

pdb

I clearly don't understand something here. I am trying to run the pdb debugger interactively w/in a Docker Container.

Here is some code:

Dockerfile:

FROM python:3.6
ENV PROJECT_DIR=/opt/foo
WORKDIR $PROJECT_DIR
COPY . .
RUN pip install -r requirements.txt
CMD ["python", "foo.py"]

foo.py:

def hello_world():
    print("hello world")
if __name__ == '__main__':
    #import pdb; pdb.set_trace()
    hello_world()

If I run docker build -t foo . and then docker run foo, it prints out "hello world" as expected.

But if I uncomment out the call to pdb.set_trace() above and try again, I get the following error:

/opt/foo/foo.py(8)<module>()
-> hello_world()
(Pdb) 
Traceback (most recent call last):
  File "foo.py", line 8, in <module>
    hello_world()
  File "foo.py", line 8, in <module>
    hello_world()
  File "/usr/local/lib/python3.6/bdb.py", line 51, in trace_dispatch
    return self.dispatch_line(frame)
  File "/usr/local/lib/python3.6/bdb.py", line 70, in dispatch_line
    if self.quitting: raise BdbQuit
bdb.BdbQuit

What am I not getting?


edit: BbdQuit raised when debugging python is not a duplicate issue.

My issue, as @soundstripe correctly identified, was not providing interactive access w/in Docker for pdb.

like image 512
trubliphone Avatar asked May 02 '19 16:05

trubliphone


People also ask

How do I run a PDB in a Python script?

Starting Python Debugger To start debugging within the program just insert import pdb, pdb. set_trace() commands. Run your script normally, and execution will stop where we have introduced a breakpoint. So basically we are hard coding a breakpoint on a line below where we call set_trace().

How do you use PDB?

Essential pdb CommandsJust enter h or help <topic> to get a list of all commands or help for a specific command or topic. Print the value of an expression. Pretty-print the value of an expression. Continue execution until the next line in the current function is reached or it returns.

What is PDB command?

The module pdb defines an interactive source code debugger for Python programs. It supports setting (conditional) breakpoints and single stepping at the source line level, inspection of stack frames, source code listing, and evaluation of arbitrary Python code in the context of any stack frame.


1 Answers

pdb expects a usable terminal with a TTY. You can run pdb easily by telling Docker to attach an interactive TTY in the container to your terminal with -it:

docker run -it foo

I usually also add the --rm option to remove my temporary containers.

docker run -it --rm foo

But that is not always best during debugging as the container is gone when you are done.

like image 140
soundstripe Avatar answered Sep 22 '22 21:09

soundstripe