Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
Add pdb support for zipapp
  • Loading branch information
gaogaotiantian committed May 2, 2024
commit 72fb51d2510303e89bfd40fff159d6d5810fa1ca
48 changes: 46 additions & 2 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
Copy Markdown
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
Copy Markdown
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
Copy Markdown
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
Copy Markdown
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 @@ -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