Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run shell command in pdb mode

Tags:

python

shell

pdb

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

*** NameError: name 'ls' is not defined

like image 317
yuxuan Avatar asked Jan 27 '16 16:01

yuxuan


3 Answers

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.

like image 162
Gilles Pion Avatar answered Oct 20 '22 21:10

Gilles Pion


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.

like image 38
Clément Avatar answered Oct 20 '22 20:10

Clément


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.

like image 1
Mr.Coffee Avatar answered Oct 20 '22 20:10

Mr.Coffee