I want to run cd
and ls
in python debugger. I try to use !ls
but I get
*** NameError: name 'ls' is not defined
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With