Skip to content

Commit 8603dfb

Browse files
bpo-42384: pdb: correctly populate sys.path[0] (GH-23338)
Automerge-Triggered-By: GH:gvanrossum
1 parent 5e45f1c commit 8603dfb

File tree

3 files changed

+45
-1
lines changed

3 files changed

+45
-1
lines changed

Lib/pdb.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1686,8 +1686,9 @@ def main():
16861686

16871687
sys.argv[:] = args # Hide "pdb.py" and pdb options from argument list
16881688

1689-
# Replace pdb's dir with script's dir in front of module search path.
16901689
if not run_as_module:
1690+
mainpyfile = os.path.realpath(mainpyfile)
1691+
# Replace pdb's dir with script's dir in front of module search path.
16911692
sys.path[0] = os.path.dirname(mainpyfile)
16921693

16931694
# Note on saving/restoring sys.argv: it's a good idea when sys.argv was

Lib/test/test_pdb.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1662,6 +1662,48 @@ def test_errors_in_command(self):
16621662
'(Pdb) ',
16631663
])
16641664

1665+
1666+
def test_issue42384(self):
1667+
'''When running `python foo.py` sys.path[0] is an absolute path. `python -m pdb foo.py` should behave the same'''
1668+
script = textwrap.dedent("""
1669+
import sys
1670+
print('sys.path[0] is', sys.path[0])
1671+
""")
1672+
commands = 'c\nq'
1673+
1674+
with os_helper.temp_cwd() as cwd:
1675+
expected = f'(Pdb) sys.path[0] is {os.path.realpath(cwd)}'
1676+
1677+
stdout, stderr = self.run_pdb_script(script, commands)
1678+
1679+
self.assertEqual(stdout.split('\n')[2].rstrip('\r'), expected)
1680+
1681+
@os_helper.skip_unless_symlink
1682+
def test_issue42384_symlink(self):
1683+
'''When running `python foo.py` sys.path[0] resolves symlinks. `python -m pdb foo.py` should behave the same'''
1684+
script = textwrap.dedent("""
1685+
import sys
1686+
print('sys.path[0] is', sys.path[0])
1687+
""")
1688+
commands = 'c\nq'
1689+
1690+
with os_helper.temp_cwd() as cwd:
1691+
cwd = os.path.realpath(cwd)
1692+
dir_one = os.path.join(cwd, 'dir_one')
1693+
dir_two = os.path.join(cwd, 'dir_two')
1694+
expected = f'(Pdb) sys.path[0] is {dir_one}'
1695+
1696+
os.mkdir(dir_one)
1697+
with open(os.path.join(dir_one, 'foo.py'), 'w') as f:
1698+
f.write(script)
1699+
os.mkdir(dir_two)
1700+
os.symlink(os.path.join(dir_one, 'foo.py'), os.path.join(dir_two, 'foo.py'))
1701+
1702+
stdout, stderr = self._run_pdb([os.path.join('dir_two', 'foo.py')], commands)
1703+
1704+
self.assertEqual(stdout.split('\n')[2].rstrip('\r'), expected)
1705+
1706+
16651707
def load_tests(*args):
16661708
from test import test_pdb
16671709
suites = [
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Make pdb populate sys.path[0] exactly the same as regular python execution.

0 commit comments

Comments
 (0)