Skip to content

Commit c10180e

Browse files
[3.8] bpo-42384: pdb: correctly populate sys.path[0] (GH-23338) (#24320)
1 parent 7370be3 commit c10180e

File tree

3 files changed

+45
-1
lines changed

3 files changed

+45
-1
lines changed

Lib/pdb.py

+2-1
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

+42
Original file line numberDiff line numberDiff line change
@@ -1658,6 +1658,48 @@ def test_errors_in_command(self):
16581658
'(Pdb) ',
16591659
])
16601660

1661+
1662+
def test_issue42384(self):
1663+
'''When running `python foo.py` sys.path[0] is an absolute path. `python -m pdb foo.py` should behave the same'''
1664+
script = textwrap.dedent("""
1665+
import sys
1666+
print('sys.path[0] is', sys.path[0])
1667+
""")
1668+
commands = 'c\nq'
1669+
1670+
with support.temp_cwd() as cwd:
1671+
expected = f'(Pdb) sys.path[0] is {os.path.realpath(cwd)}'
1672+
1673+
stdout, stderr = self.run_pdb_script(script, commands)
1674+
1675+
self.assertEqual(stdout.split('\n')[2].rstrip('\r'), expected)
1676+
1677+
@support.skip_unless_symlink
1678+
def test_issue42384_symlink(self):
1679+
'''When running `python foo.py` sys.path[0] resolves symlinks. `python -m pdb foo.py` should behave the same'''
1680+
script = textwrap.dedent("""
1681+
import sys
1682+
print('sys.path[0] is', sys.path[0])
1683+
""")
1684+
commands = 'c\nq'
1685+
1686+
with support.temp_cwd() as cwd:
1687+
cwd = os.path.realpath(cwd)
1688+
dir_one = os.path.join(cwd, 'dir_one')
1689+
dir_two = os.path.join(cwd, 'dir_two')
1690+
expected = f'(Pdb) sys.path[0] is {dir_one}'
1691+
1692+
os.mkdir(dir_one)
1693+
with open(os.path.join(dir_one, 'foo.py'), 'w') as f:
1694+
f.write(script)
1695+
os.mkdir(dir_two)
1696+
os.symlink(os.path.join(dir_one, 'foo.py'), os.path.join(dir_two, 'foo.py'))
1697+
1698+
stdout, stderr = self._run_pdb([os.path.join('dir_two', 'foo.py')], commands)
1699+
1700+
self.assertEqual(stdout.split('\n')[2].rstrip('\r'), expected)
1701+
1702+
16611703
def load_tests(*args):
16621704
from test import test_pdb
16631705
suites = [
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)