yuxuan
yuxuan

Reputation: 417

Run shell command in pdb mode

I want to run cd and ls in python debugger. I try to use !ls but I get

(Pdb) !ls
*** NameError: name 'ls' is not defined

Upvotes: 14

Views: 8427

Answers (3)

Mr.Coffee
Mr.Coffee

Reputation: 3876

PDB works very similarly to the normal python console so packages can be imported and used as you would normally do in the python interactive session.

Regarding the directory listing you should use the os module (inside the PDB, confirming each line with return aka. enter key ;) ):

from os import listdir
os.listdir("/path/to/your/folder")

Or if you want to do some more advanced stuff like start new processes or catch outputs etc. you need to have a look on subprocess module.

Upvotes: 2

Gilles Pion
Gilles Pion

Reputation: 316

Simply use the "os" module and you will able to easily execute any os command from within pdb.

Start with:

(Pdb) import os

And then:

(Pdb) os.system("ls")

or even

(Pdb) os.system("sh")

the latest simply spawns a subshell. Exiting from it returns back to debugger.

Note: the "cd" command will have no effect when used as os.system("cd dir") since it will not change the cwd of the python process. Use os.chdir("/path/to/targetdir") for that.

Upvotes: 13

Clément
Clément

Reputation: 12897

PDB doesn't let you run shell commands, unfortunately. The reason for the error that you are seeing is that PDB lets you inspect a variable name or run a one-line snippet using !. Quoting from the docs:

[!]statement

Execute the (one-line) statement in the context of the current stack frame. The exclamation point can be omitted unless the first word of the statement resembles a debugger command. To set a global variable, you can prefix the assignment command with a global command on the same line, e.g.:

(Pdb) global list_options; list_options = ['-l']
(Pdb)

Thus !ls mean "print the value of ls", which causes the NameError that you observed.

Upvotes: 4

Related Questions