0

I have a Python script that I want to be able to debug from the command line. Let's say it's called simple.py, and it contains the following code:

var1 = "Hello"
var2 = "World"
print(var1, var2)

I want to debug this. Of course I can use the debugger from the command line:

python -m pdb simple.py

But I want to debug this specifically from within another python file. I've tried using subprocess to do this, by putting this code into another script, debug.py:

import subprocess
subprocess.Popen(["bash", "-ic", "python -m pdb simple.py"])

When I run it in a Bash shell, this happens:

$ python debug.py
$ > /[path]/simple.py(1)<module>()
-> var1 = "Hello"
(Pdb) n
bash: n: command not found
$ 

So I've typed "n", expecting the debugger to move to the next line. Instead, it seems to just go straight back to Bash, and the debugger doesn't do anything.

Any idea why this happens? Is there a way to spawn a Bash shell containing a Python debugger from within a Python script, which I can actually use to debug?

1 Answer 1

1

Your debug.py finish its run and you are back to the shell (try typing ls instead, and see what happens)

What you are looking for is a way to interact with the other process, you need to get the input from your stdin and pass it to the other process stdin. It can looks something like:

import subprocess
p = subprocess.Popen(["python3", "-m", "pdb", "test.py"])

while True:
    cmd = input()
    p.stdin.write(cmd.encode())
Sign up to request clarification or add additional context in comments.

1 Comment

So I tried this as you wrote it, but said something like "File not found test.py". So then I added to the Popen argument list "bash", "-ic" to start a bash child process. Then it seems to load the debugger, but when I press "n" or anything in fact, the program ends instantly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.