Command lines for the Python interpreter and the tools that ship with it, checked against the Python 3.14.8 documentation and the pip 26.2.1 reference. Rows are grouped by task: running code, interpreter options, environment variables, virtual environments, pip, and standard-library modules started with python -m MODULE-NAME. Words in capitals are placeholders; lowercase names such as myscript.py or SomePackage come from the manuals' own examples. Windows-only py commands sit in their own group, and rarely used options are left out.
Start the interactive interpreterWith no script or interface option the interpreter opens a prompt, as if -i had been given.
python myscript.py
Run a script fileThe path may also be a directory or a zip archive that holds a __main__.py file.
python -c COMMAND
Run code given as a stringAccepts several statements separated by newlines; since 3.14 the text is dedented before it runs.
python -m MODULE-NAME
Run a module as a scriptLooks the module up on the import path, so give its name without the .py extension.
python -
Read the program from stdinTakes its commands from standard input; when that is a terminal the session becomes interactive.
python3.14
Start one specific versionThe versioned name the tutorial uses on Unix; a Microsoft Store install on Windows provides it too.
Help and version 7
Command
What it does
python -h
Show command-line helpPrints a short summary of the options and their matching environment variables, then exits.
python -?
Show help, alternate spellingDoes exactly what -h and --help do.
python --help-env
List environment variablesDescribes only the variables that are specific to Python; available since 3.11.
python --help-xoptions
List -X optionsExplains each implementation-specific value that the -X switch accepts.
python --help-all
Print the full usage textGives every piece of usage information in a single output; added in 3.11.
python -V
Print the version numberExits right after printing; --version is the long form.
python -VV
Print version and build detailsDoubling the flag adds build information such as the compiler and the build date.
Interpreter options 20
Command
What it does
python -i
Stay interactive after runningOpens a prompt once the script, -c code or -m module finishes, with its globals and any traceback available.
python -u
Unbuffer stdout and stderrOutput is written straight through; standard input is left as it was.
python -q
Hide the startup bannerLeaves out the version and copyright text when the prompt opens.
python -B
Skip writing .pyc filesImports leave no bytecode cache behind; PYTHONDONTWRITEBYTECODE does the same.
python -O
Strip assert statementsAlso drops code guarded by __debug__ and tags the cached bytecode with .opt-1.
python -OO
Strip asserts and docstringsDoes everything -O does, removes docstrings as well, and uses the .opt-2 tag.
python -E
Ignore PYTHON* variablesSettings such as PYTHONPATH and PYTHONHOME in the environment have no effect on this run.
python -I
Run in isolated modeImplies -E, -P and -s: no PYTHON* variables, no script directory and no user site-packages on sys.path.
python -P
Keep unsafe paths off sys.pathStops the script directory, or the current directory for -m and -c, from being prepended.
python -s
Leave out user site-packagesThe per-user package directory is not added to sys.path; PYTHONNOUSERSITE has the same effect.
python -S
Skip the site moduleNo site-specific paths are added at startup unless the program calls site.main() itself.
python -v
Trace module importsReports each module as it is initialised, together with the file or built-in it came from.
python -vv
Trace every import lookupDoubled, it also names every candidate file examined during the search for a module.
python -b
Warn on bytes and str mixingFlags str() on bytes without an encoding, and comparisons of bytes with str or int.
python -bb
Turn bytes warnings into errorsGiving the flag twice raises an error where the single flag only warns.
python -d
Show parser debugging outputHas an effect only on a debug build of the interpreter and is ignored elsewhere.
python -R
Randomize str and bytes hashesOnly matters when PYTHONHASHSEED holds a fixed value, because randomization is already the default.
python -x
Skip the script's first lineMeant for a first line that is not Python syntax, such as the batch-file header the manual shows.
python --check-hash-based-pycs default
Set hash-based .pyc validationThe value is default, always or never; .pyc files validated by timestamp are not affected.
python --check-hash-based-pycs always
Always validate hash-based .pycEvery hash-based cache file is compared with its source, whether it is marked checked or unchecked.
Warnings and -X options 20
Command
What it does
python -W ARG
Set a warning filterThe argument has the form action:message:category:module:lineno; trailing fields may be omitted and the option repeated.
python -Werror
Turn warnings into exceptionsApplies to every warning the process emits, including those that are ignored by default.
python -Wignore
Silence all warnings-Wi is accepted as an abbreviation of the same action.
python -Wdefault
Show each warning once per locationOverrides the built-in filters, so warnings that are normally hidden are printed too.
python -Walways
Show every warning occurrenceRepeats the message each time the same line triggers it; -Wall is a synonym.
python -W ignore::DeprecationWarning
Ignore one warning categoryEmpty fields match everything, so this filter hides DeprecationWarning from any module.
python -X dev
Enable Development ModeAdds runtime checks that are too costly to run by default; PYTHONDEVMODE does the same.
python -X importtime
Time every importPrints each module with its own time and its cumulative time including nested imports.
python -X importtime=2
Include already loaded modulesModules imported earlier are listed too, marked cached in both time columns; new in 3.14.
python -X utf8
Turn on UTF-8 ModeSetting PYTHONUTF8 to 1 in the environment switches the same mode on.
python -X utf8=0
Turn off UTF-8 ModeDisables the mode explicitly, even where it would otherwise switch on by itself.
python -X faulthandler
Dump tracebacks on a crashEnables the faulthandler module at startup; PYTHONFAULTHANDLER is the environment form.
python -X tracemalloc
Trace memory allocationsStarts the tracemalloc module at launch, keeping one frame per allocation traceback.
python -X tracemalloc=NFRAME
Trace allocations with deeper tracebacksStores up to NFRAME frames for every traced allocation.
python -X pycache_prefix=PATH
Redirect .pyc files to one treeBytecode goes to a parallel directory tree under PATH, not next to the sources.
python -X warn_default_encoding
Warn on implicit file encodingsEmits EncodingWarning whenever a file is opened with the locale's default encoding.
python -X no_debug_ranges
Drop column info from code objectsMakes code objects and .pyc files smaller and removes the position markers from tracebacks.
python -X perf
Support the Linux perf profilerLets perf report Python calls; it does nothing on platforms without support.
python -X showrefcount
Print the total reference countWorks only on debug builds, reporting at exit or after each statement at the prompt.
python -X disable_remote_debug
Disable remote debuggingBlocks the PEP 768 mechanism in both directions: scheduling code in another process and receiving it.
Environment variables 36
Python reads these variables before the command-line switches, and a switch wins where the two conflict; -E and -I make the interpreter ignore them.
Command
What it does
PYTHONPATH
Add module search directoriesUses the separator of PATH: colons on Unix, semicolons on Windows; directories that do not exist are skipped.
PYTHONHOME
Relocate the standard libraryReplaces the installation prefix under which Python looks for its own modules.
PYTHONSTARTUP
Run a file before the promptNames a file whose commands run at the start of every interactive session, in its namespace.
PYTHONUNBUFFERED
Apply -u from the environmentAny non-empty value makes stdout and stderr unbuffered for the process.
PYTHONDONTWRITEBYTECODE
Stop writing .pyc filesHas the effect of the -B option for every interpreter started with it set.
PYTHONPYCACHEPREFIX
Move the bytecode cacheCompiled files go to a mirror tree at this path, not into __pycache__ folders.
PYTHONOPTIMIZE
Apply -O from the environmentA non-empty string equals one -O; an integer equals that many.
PYTHONINSPECT
Apply -i from the environmentPython code can also set it through os.environ to force a prompt when the program ends.
PYTHONVERBOSE
Apply -v from the environmentAn integer value counts as repeating the option that many times.
PYTHONSAFEPATH
Apply -P from the environmentAny non-empty value stops Python prepending the script or current directory to sys.path.
PYTHONNOUSERSITE
Skip the user site-packagesThe per-user package directory stays off sys.path, as with the -s option.
PYTHONUSERBASE
Change the user base directoryMoves the location used by pip install --user and by the user site-packages path.
PYTHONWARNINGS
Set warning filtersHolds the same filters as -W, separated by commas; later entries win over earlier ones.
PYTHONHASHSEED
Fix or randomize the hash seedAn integer gives repeatable hashes of str and bytes; 0 switches randomization off.
PYTHONIOENCODING
Set the standard stream encodingWritten as encodingname:errorhandler, both parts optional; applies to stdin, stdout and stderr.
PYTHONUTF8
Switch UTF-8 Mode on or offUse 1 to enable and 0 to disable; any other non-empty value stops the interpreter with an error.
PYTHONBREAKPOINT
Choose the breakpoint() debuggerHolds a dotted path to a callable; unset means pdb.set_trace and 0 makes breakpoint() return at once.
PYTHONDEVMODE
Development Mode from the environmentA non-empty value has the effect of passing -X dev.
PYTHONFAULTHANDLER
Dump tracebacks on fatal signalsA fatal signal such as SIGSEGV prints the Python traceback, as with -X faulthandler.
PYTHONTRACEMALLOC
Start tracemalloc at launchThe value is the number of frames kept per traceback, so 1 stores only the latest frame.
PYTHONPROFILEIMPORTTIME
Report import timesSet to 1 for the -X importtime report, or 2 to include modules that were loaded before.
PYTHONASYNCIODEBUG
Enable asyncio debug mode
PYTHONWARNDEFAULTENCODING
Warn on implicit encodingsRaises EncodingWarning wherever the locale's default encoding is relied on.
PYTHONINTMAXSTRDIGITS
Limit int-to-string digitsSets the interpreter-wide cap on converting between very long integers and strings.
PYTHONMALLOC
Choose the memory allocatorValues such as malloc, pymalloc and debug pick the allocator family or install debug hooks.
PYTHONCASEOK
Ignore case in importsHas an effect only on Windows and macOS.
PYTHON_COLORS
Force colored output on or off1 colorizes interpreter output and 0 disables it; it outranks NO_COLOR and FORCE_COLOR.
NO_COLOR
Disable colored outputA convention other tools share; here it wins over FORCE_COLOR.
FORCE_COLOR
Force color on non-terminalsKeeps colors when output is not a terminal, for example on CI systems, whatever TERM says.
PYTHON_BASIC_REPL
Use the classic REPLAny value skips the newer Python-based prompt that depends on readline.
PYTHON_HISTORY
Move the REPL history fileOverrides the default .python_history in the home directory.
PYTHON_GIL
Force the GIL on or off1 keeps the lock; 0 removes it and needs a free-threaded build; -X gil takes precedence.
PYTHON_JIT
Toggle the experimental JITOn builds that include the just-in-time compiler, 0 disables it and 1 enables it at startup.
PYTHON_CPU_COUNT
Override the reported CPU countA positive integer replaces the CPU count that the os module reports; -X cpu_count is the switch form.
PYTHON_FROZEN_MODULES
Use or ignore frozen modulesAccepts on or off; on is the default for normal, non-debug builds.
PYTHON_DISABLE_REMOTE_DEBUG
Block remote debugger attachAny non-empty value switches off the PEP 768 remote debugging feature.
Interactive prompt 6
An end-of-file character also closes the prompt: Ctrl-D on Unix, Ctrl-Z followed by Enter on Windows.
Command
What it does
F1
Open the help browserStarts the interactive pydoc help inside the new REPL that became the default in 3.13.
F2
Browse command historyShows earlier input stripped of its output and of the prompt markers.
F3
Toggle paste modeFor multi-line code pasted from elsewhere; a second press brings back the normal prompt.
exit
Leave the interpreterIn the new REPL the bare word is enough, without call parentheses; quit works the same way.
quit()
Leave any Python promptThe tutorial's fallback when the end-of-file key does not close the prompt.
Tab
Complete namesSuggests Python keywords, local variables and module names, and attributes after a dot.
Virtual environments 14
Other shells have their own activation scripts in the same folder: activate.fish, activate.csh, Activate.ps1 for PowerShell and activate.bat for cmd.exe.
Command
What it does
python -m venv /path/to/new/virtual/environment
Create a virtual environmentCreates the directory with a pyvenv.cfg file, an interpreter copy or symlink and its own site-packages.
python -m venv -h
List venv options
python -m venv --system-site-packages ENV_DIR
Allow system packages insideThe environment can import what is installed in the base interpreter's site-packages.
python -m venv --clear ENV_DIR
Recreate an existing environmentEmpties the target directory first if it already exists.
python -m venv --upgrade ENV_DIR
Rebase onto an upgraded PythonFor use after the base Python was upgraded in place.
python -m venv --upgrade-deps ENV_DIR
Create it with the newest pipUpdates the core dependency, pip, to the latest release on PyPI during creation.
python -m venv --without-pip ENV_DIR
Create it without pipSkips the ensurepip step that normally bootstraps pip into the environment.
python -m venv --prompt PROMPT ENV_DIR
Set the activation prompt prefixReplaces the default prefix that marks the environment in the shell prompt.
python -m venv --copies ENV_DIR
Copy rather than symlink filesForces copies even on platforms where symlinks are the default.
python -m venv --symlinks ENV_DIR
Symlink rather than copy filesTries symlinks where copying is the default; the manual advises against them on Windows.
python -m venv --without-scm-ignore-files ENV_DIR
Skip the generated .gitignoreSince 3.13 a .gitignore is written into the environment unless this flag is given.
source tutorial-env/bin/activate
Activate on Unix or macOSWritten for bash; csh and fish users source activate.csh or activate.fish from the same folder.
tutorial-env\Scripts\activate
Activate on WindowsChanges the prompt and makes python start the environment's own interpreter.
deactivate
Leave the active environmentTyped into the terminal where the environment was activated.
Installing packages with pip 27
The pip rows use the short pip spelling. pip's own reference prints each command as python -m pip … on Unix and macOS and py -m pip … on Windows, which runs pip with the interpreter you name.
Command
What it does
python -m pip COMMAND
Run pip under one interpreterThe spelling pip's reference uses on Unix and macOS; its Windows examples read py -m pip.
python -m pip --version
Check which pip is activePrints the pip version, where it is installed and the Python it runs under.
python3.14 -m pip install SomePackage
Install for one Python versionOn Linux, macOS and other POSIX systems the versioned command picks the interpreter that gets the package.
py -3.14 -m pip install SomePackage
Pick the version on WindowsGoes through the py launcher to choose which installed Python receives the package.
pip install SomePackage
Install the latest versionFetches the package and its dependencies from PyPI.
pip install SomePackage==1.0.4
Install an exact versionPins the release named after the two equals signs.
pip install "SomePackage>=1.0.4"
Install a minimum versionThe double quotes stop the shell from interpreting the > character.
pip install --upgrade SomePackage
Upgrade a packageDependencies are upgraded only when they no longer meet the new requirements; -U is the short flag.
pip install -r requirements.txt
Install from a requirements fileThe option can be repeated, and a URL is accepted as well as a file.
pip install -c constraints.txt
Limit versions with a constraints fileA constraint controls which version gets installed but never causes a package to be installed.
pip install -e .
Install the current project editableEditable, or development, mode; another project path or a VCS URL can replace the dot.
pip install 'SomePackage[PDF]'
Install with optional extrasSeveral extras are separated by commas, as in SomePackage[PDF,EPUB].
Time code with a setup stepThe -s statement is executed once at the start; only the last argument is timed.
python -m timeit -n N STATEMENT
Set the loop countFixes how many times the statement runs in each measurement.
python -m timeit -r N STATEMENT
Set the number of repeatsFive measurements are taken by default.
python -m timeit -u U STATEMENT
Choose the output time unitU is one of nsec, usec, msec or sec.
python -m timeit -p STATEMENT
Measure process timeSwitches from the wall-clock timer time.perf_counter() to time.process_time().
python -m trace --count -C . somefile.py
Write line-count coverage listingsRuns the script and puts annotated listings of every imported module in the current directory.
Debugging and profiling 13
Command
What it does
python -m pdb PYFILE
Debug a scriptPauses before the first line and enters post-mortem debugging if the program exits abnormally.
python -m pdb -c COMMAND PYFILE
Run debugger commands at startEach -c command is executed as if it came from a .pdbrc file.
python -m pdb -m MODULE
Debug a moduleFinds the module the way python -m does and pauses before its first line.
python -m pdb -p 1234
Attach to a running processThe number is the process ID; attaching to a live process is new in 3.14.
python -m cProfile myscript.py
Profile a scriptPrints call counts and timings for every function when the script ends.
python -m cProfile -o OUTPUT_FILE myscript.py
Save profile data to a fileThe saved results are read back later with the pstats.Stats class.
python -m cProfile -s SORT_ORDER myscript.py
Sort the profile reportTakes a sort_stats() key and applies only when -o is not used.
python -m cProfile -m MODULE
Profile a module
python -X importtime -c 'import asyncio'
Profile the imports of one moduleThe manual's typical usage: import a module with -c and read the per-import timings.
python -X dev script.py README.txt
Run a script in Development ModeIn the manual example this reveals a ResourceWarning for a file that was never closed.
python -X dev -X tracemalloc=5 script.py README.rst
Find where a leaked file was openedWith tracemalloc enabled the warning includes the traceback of the allocation.
python -m asyncio ps PID
List tasks of a running processReads the task state of the other process without executing any code in it.
python -m asyncio pstree PID
Show the task tree of a process
Windows py command 9
Command
What it does
py
Launch the default runtimeBehaves like python by default and can replace it in any command.
py -V:3.14
Launch a specific versionThe tag option has to come first; official releases can also be written without the V: part.
py list
List installed runtimesTags can be added as filters, and --one prints just the runtime that would be launched.
py list --online 3.14
List installable runtimesSearches the online index for versions that py install could add.
py install TAG
Install a runtimeSeveral tags may be given; the special tag default selects the default runtime.
py install --update
Update installed runtimesWithout tags, every runtime the install manager manages is replaced when a newer version exists.
py uninstall TAG
Remove a runtimeAsks for confirmation unless --yes is passed.
py uninstall --purge
Remove all managed runtimesAlso cleans up the Start menu, the registry and any download caches.
py help
Show install manager commandspy help install, or -? after a command, prints the help of one subcommand.
No row on this page matches that filter.
Notes
Running the interpreter
python myscript.py runs a file and python -c COMMAND runs code passed as a string, but the flag to learn is python -m MODULE-NAME: it runs a module as a script from the interpreter's own environment, so python -m pip, python -m venv and python -m http.server always use the Python you invoked rather than whatever is first on PATH. python -i drops into a REPL after the script finishes with its variables intact, which is the cheapest debugger there is. python -u unbuffers stdout and stderr and is what container logs need to show output promptly.
Isolation and diagnostics
python -I runs in isolated mode — no user site-packages, no PYTHON* environment variables, no script directory on the path — and is the right way to run system tools that must not be affected by a user's packages. python -E, python -P and python -s apply those restrictions separately. python -v prints every module import, which answers "which file is actually being imported" when two copies of a package exist. python -O strips asserts and python -B stops writing .pyc files. The -X switch carries implementation options: python -X dev adds extra runtime checks and python -X importtime prints a startup import profile.
pip install
pip install -r requirements.txt installs a requirements file and pip install -c constraints.txt limits versions from a constraints file without installing anything by itself, which is how a team keeps one set of pins across projects. pip install -e . installs a project in editable mode so source edits take effect without reinstalling — the standard setup for a package you are developing. pip install --upgrade SomePackage upgrades, pip install --dry-run shows what would change first, and pip install --no-deps installs a single package without touching its dependencies. pip install --user installs into the user directory when a system Python is not writable; a virtual environment is the better fix.
Questions
Why should I use python -m pip instead of pip?
It guarantees pip runs in the same interpreter as python. Plain pip may belong to a different Python on PATH, which is the usual cause of "installed but import fails".
How do I inspect variables after a script crashes?
Run it with python -i script.py. When the script ends or raises, you get a prompt with its namespace loaded.
What is editable mode?
pip install -e . links the project source into site-packages instead of copying it, so changes are live without reinstalling.
How do I see which file a module is imported from?
python -v prints each import with its path, or run python -c "import x; print(x.__file__)".