Skip to content

gh-118500: Add pdb support for zipapp #118501

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
May 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions Doc/whatsnew/3.13.rst
Original file line number Diff line number Diff line change
Expand Up @@ -687,6 +687,9 @@ pdb
command line option or :envvar:`PYTHONSAFEPATH` environment variable).
(Contributed by Tian Gao and Christian Walther in :gh:`111762`.)

* :mod:`zipapp` is supported as a debugging target.
(Contributed by Tian Gao in :gh:`118501`.)

queue
-----

Expand Down
50 changes: 47 additions & 3 deletions Lib/pdb.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,10 @@ def find_function(funcname, filename):
try:
fp = tokenize.open(filename)
except OSError:
return None
lines = linecache.getlines(filename)
if not lines:
return None
fp = io.StringIO(''.join(lines))
funcdef = ""
funcstart = None
# consumer of this info expects the first line to be 1
Expand Down Expand Up @@ -237,6 +240,44 @@ def namespace(self):
)


class _ZipTarget(_ExecutableTarget):
def __init__(self, target):
import runpy

self._target = os.path.realpath(target)
sys.path.insert(0, self._target)
try:
_, self._spec, self._code = runpy._get_main_module_details()
except ImportError as e:
print(f"ImportError: {e}")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do you need to special-case ImportError here?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's from #108791. This is a very common case but the exception traceback would be very large because it's generated rather deeply and it distracts users. It would be a better experience to simply show that there's an import error when the user passes in an invalid module.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok. there is also traceback.format_exception_only().

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah I think the orignal thought here was just to suppress the common import error, and leave the others be. In that case we need a special case for ImportError anyway with or without format_exception_only.

sys.exit(1)
except Exception:
traceback.print_exc()
sys.exit(1)

def __repr__(self):
return self._target

@property
def filename(self):
return self._code.co_filename

@property
def code(self):
return self._code

@property
def namespace(self):
return dict(
__name__='__main__',
__file__=os.path.normcase(os.path.abspath(self.filename)),
__package__=self._spec.parent,
__loader__=self._spec.loader,
__spec__=self._spec,
__builtins__=__builtins__,
)


class _PdbInteractiveConsole(code.InteractiveConsole):
def __init__(self, ns, message):
self._message = message
Expand Down Expand Up @@ -1076,7 +1117,7 @@ def lineinfo(self, identifier):
if f:
fname = f
item = parts[1]
answer = find_function(item, fname)
answer = find_function(item, self.canonic(fname))
return answer or failed

def checkline(self, filename, lineno):
Expand Down Expand Up @@ -2276,7 +2317,10 @@ def main():
if not opts.args:
parser.error("no module or script to run")
file = opts.args.pop(0)
target = _ScriptTarget(file)
if file.endswith('.pyz'):
target = _ZipTarget(file)
else:
target = _ScriptTarget(file)

sys.argv[:] = [file] + opts.args # Hide "pdb.py" and pdb options from argument list

Expand Down
25 changes: 25 additions & 0 deletions Lib/test/test_pdb.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import subprocess
import textwrap
import linecache
import zipapp

from contextlib import ExitStack, redirect_stdout
from io import StringIO
Expand Down Expand Up @@ -3492,6 +3493,30 @@ def test_non_utf8_encoding(self):
if filename.endswith(".py"):
self._run_pdb([os.path.join(script_dir, filename)], 'q')

def test_zipapp(self):
with os_helper.temp_dir() as temp_dir:
os.mkdir(os.path.join(temp_dir, 'source'))
script = textwrap.dedent(
"""
def f(x):
return x + 1
f(21 + 21)
"""
)
with open(os.path.join(temp_dir, 'source', '__main__.py'), 'w') as f:
f.write(script)
zipapp.create_archive(os.path.join(temp_dir, 'source'),
os.path.join(temp_dir, 'zipapp.pyz'))
stdout, _ = self._run_pdb([os.path.join(temp_dir, 'zipapp.pyz')], '\n'.join([
'b f',
'c',
'p x',
'q'
]))
self.assertIn('42', stdout)
self.assertIn('return x + 1', stdout)


class ChecklineTests(unittest.TestCase):
def setUp(self):
linecache.clearcache() # Pdb.checkline() uses linecache.getline()
Expand Down
2 changes: 1 addition & 1 deletion Lib/test/test_pyclbr.py
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ def test_others(self):
cm(
'pdb',
# pyclbr does not handle elegantly `typing` or properties
ignore=('Union', '_ModuleTarget', '_ScriptTarget'),
ignore=('Union', '_ModuleTarget', '_ScriptTarget', '_ZipTarget'),
)
cm('pydoc', ignore=('input', 'output',)) # properties

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add :mod:`pdb` support for zipapps