Skip to content

Instantly share code, notes, and snippets.

@wware
Last active July 5, 2019 16:49
Show Gist options
  • Save wware/3655ef2607f475df1e7fded47744d438 to your computer and use it in GitHub Desktop.
Save wware/3655ef2607f475df1e7fded47744d438 to your computer and use it in GitHub Desktop.

Getting to a Bash prompt from inside PDB

Sometimes I'm doing stuff in PDB, the Python debugger, and I would like to hop out to a Bash prompt. Maybe I want to see what is the current directory, or what files are in the current directory, or I'd like to run some executable in this environment, or see what is on the current path. Anyway the trick is to do this.

$ python -m pdb foo.py 
> /Users/wware/foo.py(3)<module>()
-> import os
(Pdb) n
> /Users/wware/foo.py(4)<module>()
-> import time
(Pdb) os.system("/bin/bash -")
bash-3.2$ pwd
/Users/wware
bash-3.2$ ls *.py
foo.py			hack.py			bar.py			baz.p	views.py
bash-3.2$ exit
exit
0
(Pdb) n
> /Users/wware/foo.py(5)<module>()
-> some more python....
(Pdb) q

As a one-liner you have

> import os; os.system("/bin/bash -")

You might want to use os.environ['SHELL'] instead of /bin/bash in case the shell is elsewhere, or in case for some bizarre reason you want some shell other than Bash.

This can also be an alias in a .pdbrc file. This will allow you to use "sh" as a PDB command that puts you into a Bash session.

alias sh import os; os.system(os.environ['SHELL'] + ' -')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment