Skip to content

[hmr] Consider adding -P flag for CLI usage #514

@CNSeniorious000

Description

@CNSeniorious000

Background

Python 3.11 introduced -P flag to prevent unsafe paths in sys.path [What's New] [PEP 587] [CLI docs].

Official Definition: Prevents Python from automatically prepending potentially unsafe paths to sys.path.

Enable via:

Behavior [Python docs]:

  • python script.py: doesn't prepend script's directory
  • python -m module: doesn't prepend current working directory
  • python -c code and python (REPL): doesn't prepend empty string (current directory)

Design Goals

From official proposals [PEP 587] and discussions:

  1. Security: Prevents malicious local modules from being accidentally imported
  2. Path injection protection: Stops local directories from shadowing stdlib packages [CPython #95754] [Better errors PR #113769]
  3. Consistency: Aligns interactive environments with command-line behavior

Historical Context

GitHub issue #57684 tracked this feature request:

  • Original proposal: --mainpath/--nomainpath command-line options
  • Evolution: -P flag and PYTHONSAFEENV (later renamed PYTHONSAFEPATH) [BPO #13475]
  • Core maintainers: Victor Stinner et al.
  • Implementation: [initconfig.c] [PyConfig.safe_path]

Industry Adoption

  • IPython 9.7: Added PYTHONSAFEPATH support [changelog] [PR #15014]
  • pdb: Respects safe_path behavior [PR #111762]
  • IPython aligns with Python's native security without requiring separate --ignore_cwd configuration

Proposal

Add -P/--safe-path flag and PYTHONSAFEPATH support to our Python execution environment. This aligns with Python standards and improves security—critical for web-based Python consoles handling untrusted code.

Why This Matters

Python's official security enhancement prevents dependency path attacks in multi-user or untrusted environments. As an online IDE, implementing this feature would protect users from module shadowing vulnerabilities.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions