Python commands

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.

297 commands in 16 sections. Checked row by row against Python 3.14.8 documentation: Command line and environment on . Edited by Jay.

Running code 6

CommandWhat it does
pythonStart the interactive interpreterWith no script or interface option the interpreter opens a prompt, as if -i had been given.
python myscript.pyRun a script fileThe path may also be a directory or a zip archive that holds a __main__.py file.
python -c COMMANDRun code given as a stringAccepts several statements separated by newlines; since 3.14 the text is dedented before it runs.
python -m MODULE-NAMERun 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.14Start one specific versionThe versioned name the tutorial uses on Unix; a Microsoft Store install on Windows provides it too.

Help and version 7

CommandWhat it does
python -hShow 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-envList environment variablesDescribes only the variables that are specific to Python; available since 3.11.
python --help-xoptionsList -X optionsExplains each implementation-specific value that the -X switch accepts.
python --help-allPrint the full usage textGives every piece of usage information in a single output; added in 3.11.
python -VPrint the version numberExits right after printing; --version is the long form.
python -VVPrint version and build detailsDoubling the flag adds build information such as the compiler and the build date.

Interpreter options 20

CommandWhat it does
python -iStay interactive after runningOpens a prompt once the script, -c code or -m module finishes, with its globals and any traceback available.
python -uUnbuffer stdout and stderrOutput is written straight through; standard input is left as it was.
python -qHide the startup bannerLeaves out the version and copyright text when the prompt opens.
python -BSkip writing .pyc filesImports leave no bytecode cache behind; PYTHONDONTWRITEBYTECODE does the same.
python -OStrip assert statementsAlso drops code guarded by __debug__ and tags the cached bytecode with .opt-1.
python -OOStrip asserts and docstringsDoes everything -O does, removes docstrings as well, and uses the .opt-2 tag.
python -EIgnore PYTHON* variablesSettings such as PYTHONPATH and PYTHONHOME in the environment have no effect on this run.
python -IRun in isolated modeImplies -E, -P and -s: no PYTHON* variables, no script directory and no user site-packages on sys.path.
python -PKeep unsafe paths off sys.pathStops the script directory, or the current directory for -m and -c, from being prepended.
python -sLeave out user site-packagesThe per-user package directory is not added to sys.path; PYTHONNOUSERSITE has the same effect.
python -SSkip the site moduleNo site-specific paths are added at startup unless the program calls site.main() itself.
python -vTrace module importsReports each module as it is initialised, together with the file or built-in it came from.
python -vvTrace every import lookupDoubled, it also names every candidate file examined during the search for a module.
python -bWarn on bytes and str mixingFlags str() on bytes without an encoding, and comparisons of bytes with str or int.
python -bbTurn bytes warnings into errorsGiving the flag twice raises an error where the single flag only warns.
python -dShow parser debugging outputHas an effect only on a debug build of the interpreter and is ignored elsewhere.
python -RRandomize str and bytes hashesOnly matters when PYTHONHASHSEED holds a fixed value, because randomization is already the default.
python -xSkip 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 defaultSet hash-based .pyc validationThe value is default, always or never; .pyc files validated by timestamp are not affected.
python --check-hash-based-pycs alwaysAlways 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

CommandWhat it does
python -W ARGSet a warning filterThe argument has the form action:message:category:module:lineno; trailing fields may be omitted and the option repeated.
python -WerrorTurn warnings into exceptionsApplies to every warning the process emits, including those that are ignored by default.
python -WignoreSilence all warnings-Wi is accepted as an abbreviation of the same action.
python -WdefaultShow each warning once per locationOverrides the built-in filters, so warnings that are normally hidden are printed too.
python -WalwaysShow every warning occurrenceRepeats the message each time the same line triggers it; -Wall is a synonym.
python -W ignore::DeprecationWarningIgnore one warning categoryEmpty fields match everything, so this filter hides DeprecationWarning from any module.
python -X devEnable Development ModeAdds runtime checks that are too costly to run by default; PYTHONDEVMODE does the same.
python -X importtimeTime every importPrints each module with its own time and its cumulative time including nested imports.
python -X importtime=2Include already loaded modulesModules imported earlier are listed too, marked cached in both time columns; new in 3.14.
python -X utf8Turn on UTF-8 ModeSetting PYTHONUTF8 to 1 in the environment switches the same mode on.
python -X utf8=0Turn off UTF-8 ModeDisables the mode explicitly, even where it would otherwise switch on by itself.
python -X faulthandlerDump tracebacks on a crashEnables the faulthandler module at startup; PYTHONFAULTHANDLER is the environment form.
python -X tracemallocTrace memory allocationsStarts the tracemalloc module at launch, keeping one frame per allocation traceback.
python -X tracemalloc=NFRAMETrace allocations with deeper tracebacksStores up to NFRAME frames for every traced allocation.
python -X pycache_prefix=PATHRedirect .pyc files to one treeBytecode goes to a parallel directory tree under PATH, not next to the sources.
python -X warn_default_encodingWarn on implicit file encodingsEmits EncodingWarning whenever a file is opened with the locale's default encoding.
python -X no_debug_rangesDrop column info from code objectsMakes code objects and .pyc files smaller and removes the position markers from tracebacks.
python -X perfSupport the Linux perf profilerLets perf report Python calls; it does nothing on platforms without support.
python -X showrefcountPrint the total reference countWorks only on debug builds, reporting at exit or after each statement at the prompt.
python -X disable_remote_debugDisable 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.

CommandWhat it does
PYTHONPATHAdd module search directoriesUses the separator of PATH: colons on Unix, semicolons on Windows; directories that do not exist are skipped.
PYTHONHOMERelocate the standard libraryReplaces the installation prefix under which Python looks for its own modules.
PYTHONSTARTUPRun a file before the promptNames a file whose commands run at the start of every interactive session, in its namespace.
PYTHONUNBUFFEREDApply -u from the environmentAny non-empty value makes stdout and stderr unbuffered for the process.
PYTHONDONTWRITEBYTECODEStop writing .pyc filesHas the effect of the -B option for every interpreter started with it set.
PYTHONPYCACHEPREFIXMove the bytecode cacheCompiled files go to a mirror tree at this path, not into __pycache__ folders.
PYTHONOPTIMIZEApply -O from the environmentA non-empty string equals one -O; an integer equals that many.
PYTHONINSPECTApply -i from the environmentPython code can also set it through os.environ to force a prompt when the program ends.
PYTHONVERBOSEApply -v from the environmentAn integer value counts as repeating the option that many times.
PYTHONSAFEPATHApply -P from the environmentAny non-empty value stops Python prepending the script or current directory to sys.path.
PYTHONNOUSERSITESkip the user site-packagesThe per-user package directory stays off sys.path, as with the -s option.
PYTHONUSERBASEChange the user base directoryMoves the location used by pip install --user and by the user site-packages path.
PYTHONWARNINGSSet warning filtersHolds the same filters as -W, separated by commas; later entries win over earlier ones.
PYTHONHASHSEEDFix or randomize the hash seedAn integer gives repeatable hashes of str and bytes; 0 switches randomization off.
PYTHONIOENCODINGSet the standard stream encodingWritten as encodingname:errorhandler, both parts optional; applies to stdin, stdout and stderr.
PYTHONUTF8Switch UTF-8 Mode on or offUse 1 to enable and 0 to disable; any other non-empty value stops the interpreter with an error.
PYTHONBREAKPOINTChoose the breakpoint() debuggerHolds a dotted path to a callable; unset means pdb.set_trace and 0 makes breakpoint() return at once.
PYTHONDEVMODEDevelopment Mode from the environmentA non-empty value has the effect of passing -X dev.
PYTHONFAULTHANDLERDump tracebacks on fatal signalsA fatal signal such as SIGSEGV prints the Python traceback, as with -X faulthandler.
PYTHONTRACEMALLOCStart tracemalloc at launchThe value is the number of frames kept per traceback, so 1 stores only the latest frame.
PYTHONPROFILEIMPORTTIMEReport import timesSet to 1 for the -X importtime report, or 2 to include modules that were loaded before.
PYTHONASYNCIODEBUGEnable asyncio debug mode
PYTHONWARNDEFAULTENCODINGWarn on implicit encodingsRaises EncodingWarning wherever the locale's default encoding is relied on.
PYTHONINTMAXSTRDIGITSLimit int-to-string digitsSets the interpreter-wide cap on converting between very long integers and strings.
PYTHONMALLOCChoose the memory allocatorValues such as malloc, pymalloc and debug pick the allocator family or install debug hooks.
PYTHONCASEOKIgnore case in importsHas an effect only on Windows and macOS.
PYTHON_COLORSForce colored output on or off1 colorizes interpreter output and 0 disables it; it outranks NO_COLOR and FORCE_COLOR.
NO_COLORDisable colored outputA convention other tools share; here it wins over FORCE_COLOR.
FORCE_COLORForce color on non-terminalsKeeps colors when output is not a terminal, for example on CI systems, whatever TERM says.
PYTHON_BASIC_REPLUse the classic REPLAny value skips the newer Python-based prompt that depends on readline.
PYTHON_HISTORYMove the REPL history fileOverrides the default .python_history in the home directory.
PYTHON_GILForce the GIL on or off1 keeps the lock; 0 removes it and needs a free-threaded build; -X gil takes precedence.
PYTHON_JITToggle the experimental JITOn builds that include the just-in-time compiler, 0 disables it and 1 enables it at startup.
PYTHON_CPU_COUNTOverride the reported CPU countA positive integer replaces the CPU count that the os module reports; -X cpu_count is the switch form.
PYTHON_FROZEN_MODULESUse or ignore frozen modulesAccepts on or off; on is the default for normal, non-debug builds.
PYTHON_DISABLE_REMOTE_DEBUGBlock 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.

CommandWhat it does
F1Open the help browserStarts the interactive pydoc help inside the new REPL that became the default in 3.13.
F2Browse command historyShows earlier input stripped of its output and of the prompt markers.
F3Toggle paste modeFor multi-line code pasted from elsewhere; a second press brings back the normal prompt.
exitLeave 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.
TabComplete 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.

CommandWhat it does
python -m venv /path/to/new/virtual/environmentCreate a virtual environmentCreates the directory with a pyvenv.cfg file, an interpreter copy or symlink and its own site-packages.
python -m venv -hList venv options
python -m venv --system-site-packages ENV_DIRAllow system packages insideThe environment can import what is installed in the base interpreter's site-packages.
python -m venv --clear ENV_DIRRecreate an existing environmentEmpties the target directory first if it already exists.
python -m venv --upgrade ENV_DIRRebase onto an upgraded PythonFor use after the base Python was upgraded in place.
python -m venv --upgrade-deps ENV_DIRCreate it with the newest pipUpdates the core dependency, pip, to the latest release on PyPI during creation.
python -m venv --without-pip ENV_DIRCreate it without pipSkips the ensurepip step that normally bootstraps pip into the environment.
python -m venv --prompt PROMPT ENV_DIRSet the activation prompt prefixReplaces the default prefix that marks the environment in the shell prompt.
python -m venv --copies ENV_DIRCopy rather than symlink filesForces copies even on platforms where symlinks are the default.
python -m venv --symlinks ENV_DIRSymlink 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_DIRSkip the generated .gitignoreSince 3.13 a .gitignore is written into the environment unless this flag is given.
source tutorial-env/bin/activateActivate on Unix or macOSWritten for bash; csh and fish users source activate.csh or activate.fish from the same folder.
tutorial-env\Scripts\activateActivate on WindowsChanges the prompt and makes python start the environment's own interpreter.
deactivateLeave 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.

CommandWhat it does
python -m pip COMMANDRun pip under one interpreterThe spelling pip's reference uses on Unix and macOS; its Windows examples read py -m pip.
python -m pip --versionCheck which pip is activePrints the pip version, where it is installed and the Python it runs under.
python3.14 -m pip install SomePackageInstall 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 SomePackagePick the version on WindowsGoes through the py launcher to choose which installed Python receives the package.
pip install SomePackageInstall the latest versionFetches the package and its dependencies from PyPI.
pip install SomePackage==1.0.4Install 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 SomePackageUpgrade a packageDependencies are upgraded only when they no longer meet the new requirements; -U is the short flag.
pip install -r requirements.txtInstall from a requirements fileThe option can be repeated, and a URL is accepted as well as a file.
pip install -c constraints.txtLimit 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].
pip install './downloads/SomePackage-1.0.4.tar.gz'Install a local source archiveA URL of an archive works in the same position.
pip install 'SomeProject@git+https://git.repo/[email protected]'Install from a Git repository
pip install --userInstall into the user directoryTargets the per-user location, typically ~/.local/ on Unix and %APPDATA%Python on Windows.
pip install --preAllow pre-release versionsWithout it pip considers stable releases only.
pip install --no-depsSkip dependency installationOnly the named packages are installed; what they depend on is left alone.
pip install --dry-runPreview without installingPrints what would be installed; adding --ignore-installed makes it resolve every requirement afresh.
pip install --force-reinstallReinstall packagesPackages are installed again even when the current version is already up to date.
pip install -t DIRInstall into a target directoryExisting files in the directory are kept unless --upgrade is added.
pip install --no-indexIgnore the package indexOnly the locations given with --find-links are searched.
pip install --no-index --find-links=/local/dir/ SomePackageInstall from a local directoryLooks for archives in the directory and does not contact any index.
pip install --index-url http://my.package.repo/simple/ SomePackageInstall from another indexReplaces PyPI as the index for this command; -i is the short flag.
pip install --extra-index-url http://my.package.repo/simple SomePackageSearch an additional indexThe extra index is consulted alongside PyPI; the reference warns that this can be unsafe.
python -m pip install --upgrade pipUpgrade pip itselfThe Windows form in the same guide is py -m pip install --upgrade pip.
python -m ensurepip --upgradeBootstrap or update pipInstalls the bundled pip when it is missing and makes sure it is at least as new as that copy.
python -m ensurepip --default-pipRestore a missing pip commandSuggested by the installing guide when pip was not installed; also creates the plain pip script.

pip install options 33

CommandWhat it does
pip install --build-constraint build-constraints.txt SomePackageConstrain build dependenciesAffects only the packages used while building, not what ends up installed.
pip install --requirements-from-script FILEInstall a script's dependenciesReads the inline metadata block that PEP 723 defines inside the script file.
pip install SomePackage --only-depsInstall only the dependenciesThe named package itself is left out; not available with the legacy resolver.
pip install --group groupAInstall a dependency groupReads the group from the [dependency-groups] table of pyproject.toml in the current directory.
pip install --upgrade-strategy UPGRADE_STRATEGYChoose how dependencies upgradeonly-if-needed is the default; eager upgrades dependencies even when they already satisfy the requirement.
pip install -IOverwrite installed packagesIgnores what is already installed and writes over it; the reference warns this can break a system.
pip install --ignore-requires-pythonIgnore Requires-Python metadataSkips the check of a package's declared Python version range.
pip install --platform PLATFORMTarget another platformRestricts the choice to wheels built for that platform; repeat it to allow several.
pip install --python-version PYTHON_VERSIONTarget another Python versionGiven as up to three dot-separated integers such as 3.7; defaults to the running interpreter's version.
pip install --implementation IMPLEMENTATIONTarget a Python implementationTakes a tag such as cp, pp, jy or ip; py forces implementation-agnostic wheels.
pip install --abi ABITarget a Python ABIUsually needs the platform, implementation and Python version options next to it.
pip install --root DIRInstall under an alternate rootEvery path is created relative to the given root directory.
pip install --prefix DIRInstall under a prefixCreates lib, bin and the rest under that folder; installed scripts still point at pip's own interpreter.
pip install --src DIRChoose the editable checkout folderWhere VCS projects installed with -e are checked out; src inside the virtualenv by default.
pip install --no-build-isolationBuild without isolationBuild dependencies declared by the project must then be installed already.
pip install --check-build-dependenciesCheck build dependencies
pip install -C SETTINGSPass settings to the build backendWritten as KEY=VALUE; repeat the option to hand over several keys.
pip install --no-cleanKeep build directories
pip install --compileCompile sources to bytecode
pip install --no-compileSkip bytecode compilationThe installed source files are not compiled as part of the install.
pip install --break-system-packagesOverride the externally-managed lockLets pip change an installation that is marked EXTERNALLY-MANAGED.
pip install --root-user-action ROOT_USER_ACTIONSet behaviour when run as rootEither warn, which is the default, or ignore.
pip install --no-warn-script-locationSilence the script PATH warningSuppresses the notice shown when scripts land in a directory that is not on PATH.
pip install --no-warn-conflictsSilence dependency conflict warningsNo message is printed about broken dependencies after the install.
pip install --require-hashesRequire hashes for every packageEach requirement must carry a hash to be verified; implied when a requirements file contains --hash.
pip install --progress-bar PROGRESS_BARControl the progress barValues are auto, on, off and raw; in auto mode --quiet hides the bar.
pip install --report FILEWrite a JSON install reportDescribes what pip did; a dash as the file name sends the report to stdout.
pip install --uploaded-prior-to=P3D SomePackageIgnore recently uploaded releasesTakes an ISO 8601 date-time or a duration in days; P3D means at least three days old.
pip install --all-releases=:all: SomePackageAllow pre-releases for all packagesA package name in place of :all: limits the permission to that package.
pip install --only-final=:all: SomePackageAllow final releases onlyTurns pre-releases off; a package name in place of :all: narrows it to that package.
pip install SomePackage1 SomePackage2 --no-binary :all:Install from source onlyNo wheels are used; naming a package in place of :all: applies it to that package alone.
pip install --only-binary FORMAT_CONTROLInstall from wheels onlyTakes :all:, :none: or package names; a package without a wheel then fails to install.
pip install --prefer-binaryPrefer wheels over newer sourcesA binary package is chosen even when a newer source release exists.

Inspecting and removing packages 21

CommandWhat it does
pip listList installed packagesShows names and versions in case-insensitive alphabetical order, editable installs included.
pip list --outdatedList packages with newer releasesAdds columns for the latest available version and its distribution type.
pip list --not-requiredList packages nothing depends on
pip list --editableList editable installs
pip list --format=jsonList packages as JSONThe format option also accepts columns, the default, and freeze.
pip show PACKAGEShow details of a packagePrints the metadata, including the install location and requirements, in mail-header style.
pip show --files PACKAGEList a package's installed files
pip show --verbose sphinxShow extended package metadataAdds fields such as the installer, classifiers and entry points.
pip freezePrint packages as requirementsLeaves out pip itself on Python 3.12 and later unless --all is given.
pip freeze > requirements.txtSave the environment to a fileThe file can be replayed in another environment with pip install -r requirements.txt.
pip checkVerify dependency compatibilityReports packages whose requirements are missing or installed in a conflicting version.
pip inspectReport the environment as JSON
pip uninstall SomePackageRemove a packageAsks for confirmation before deleting the files it lists.
pip uninstall -yUninstall without confirmation
pip uninstall -r FILEUninstall everything in a fileRemoves all the packages listed in the given requirements file.
pip download SomePackageDownload without installingResolves like pip install but saves the distributions to the current directory.
pip download -d . SomePackageDownload into a chosen folderThe dot is the current directory, which is also where files go without -d.
pip wheel --wheel-dir=/tmp/wheelhouse SomePackageBuild wheels into a directoryBuilds wheel archives for the requirement and for its dependencies.
pip index versions PACKAGEList versions on the index
pip hash FILEHash a package archiveThe digest can follow --hash in a requirements file to make installs repeatable.
pip lock -e .Write a lock file (experimental)Marked experimental; the result is only guaranteed valid for the current Python version and platform.

pip configuration and cache 12

CommandWhat it does
pip config listShow the active configurationA file option, --global, --user or --site, limits the list to one configuration file.
pip config get command.optionRead one settingKeys are a command name and an option joined by a dot; global stands for every command.
pip config set global.index-url https://example.org/Set an option for all commandsThe global prefix makes the index URL apply to every pip command.
pip config set download.timeout 10Set an option for one commandHere the ten-second timeout is used by pip download only.
pip config unset command.optionRemove a setting
pip config editOpen the config file in an editorThe --editor option names the program that opens the file.
pip config debugList config files and their values
pip cache dirShow the cache directory
pip cache infoShow cache statistics
pip cache listList cached wheel filesA glob expression or package name after it narrows the list.
pip cache remove PATTERNDelete matching cache entries
pip cache purgeEmpty the cache

pip general options 12

CommandWhat it does
pip -hShow pip help
pip -vPrint more outputAdditive: it can be given up to three times.
pip -qPrint less outputOne, two or three flags limit messages to warnings, errors or critical errors.
pip --python PYTHONRun pip for another interpreter
pip --require-virtualenvRefuse to run outside a venvpip exits with an error when no virtual environment is active.
pip --isolatedIgnore environment and user config
pip --no-cache-dirTurn the cache off
pip --no-inputNever prompt for input
pip --proxy PROXYUse a proxy serverThe value is a URL: a scheme, optional user and password, then the proxy host and port.
pip --trusted-host HOSTNAMETrust a host without valid HTTPSAccepts a host name or a host:port pair.
pip --timeout SECSet the socket timeoutFifteen seconds is the default wait on a socket.
pip --disable-pip-version-checkSkip the pip update checkStops the periodic look-up on PyPI for a newer pip; implied by --no-index.

Standard library tools 42

CommandWhat it does
python -m http.serverServe the current directoryListens on port 8000 on all interfaces unless told otherwise.
python -m http.server 9000Serve on another port
python -m http.server --bind 127.0.0.1Serve to this machine onlyBinds to localhost; IPv4 and IPv6 addresses are both accepted.
python -m http.server --directory /tmp/Serve a chosen directory
python -m http.server --protocol HTTP/1.1Serve with HTTP/1.1The server speaks HTTP/1.0 unless this is set.
python -m http.server --tls-cert fullchain.pemServe over HTTPSNew in 3.14; --tls-key adds a private key file kept apart from the certificate chain.
python -m json mp_films.jsonValidate and pretty-print a JSON fileWithout a file name the text is read from standard input.
echo '{"json": "obj"}' | python -m jsonPretty-print JSON from a pipe
python -m json --sort-keysSort JSON keys alphabeticallyWithout it the output keeps the key order of the input.
python -m json.toolOlder name of the JSON toolStill supported, but since 3.14 the same interface runs as python -m json.
python -m zipapp myappPack a directory into a .pyzThe result, myapp.pyz, is run with python myapp.pyz.
python -m zipapp myapp -m "myapp:main"Pack with an entry pointWrites a __main__.py that calls the given pkg.mod:fn function.
python -m zipapp myapp -p "/usr/bin/env python"Pack an executable archiveAdds a #! line with that interpreter and, on POSIX, marks the file executable.
python -m zipfile -c monty.zip spam.txt eggs.txtCreate a zip archiveA directory can be given in place of the file names.
python -m zipfile -e monty.zip target-dir/Extract a zip archive
python -m zipfile -l monty.zipList a zip archive
python -m tarfile -c monty.tar spam.txt eggs.txtCreate a tar archive
python -m tarfile -e monty.tarExtract a tar archiveUnpacks into the current directory; add a directory name to extract elsewhere.
python -m tarfile -l monty.tarList a tar archive
python -m compileallPrecompile sources to bytecodeWith no argument it compiles the directories on sys.path without descending into them.
python -m compileall DIRECTORY -lCompile one directory levelThe same as -r 0: subdirectories are not visited.
python -m sitePrint sys.path and user directoriesLists sys.path, then USER_BASE and USER_SITE with a note on whether each directory exists.
python -m site --user-sitePrint the user site-packages pathThe companion option --user-base prints the user base directory.
python -m sysconfigPrint build and path configurationShows the platform, the Python version, the installation scheme and its paths.
python -m pydoc sysRead module documentationShows the text in the style of a Unix man page; a function, class or package name works too.
python -m pydoc -p 1234Browse docs on a local portServes the documentation at http://localhost:1234/; port 0 picks any free port.
python -m pydoc -bOpen the docs in a browserStarts the documentation server and opens the module index page.
python -m webbrowser -t "https://www.python.org"Open a URL in a browser tabWith -n the page opens in a new window when the browser allows it.
python -m calendar 2000Print a calendar for a year
python -m uuidGenerate a random UUIDUses uuid4() unless -u names another function.
python -m random 6Print a random integerGives a whole number from 1 to the argument, both included; a float argument gives a random float.
python -m sqlite3 FILENAMEOpen a SQLite shellLeave the shell with .quit or Ctrl-D; an SQL statement can follow the file name.
python -m asyncioStart the asyncio REPLawait can be used directly at this prompt.
python -m dis INFILEDisassemble a source fileWithout a file name the source is read from standard input.
python -m ast INFILEPrint a file's syntax treeParses the file and dumps the tree to stdout; -a adds line and column attributes.
python -m tokenize hello.pyPrint the tokens of a file
python -m mimetypes filename.pngGuess a file's MIME typeWith -e the argument is a type and the answer is an extension.
python -m platformPrint the platform string
python -m pickletools x.pickleDisassemble a pickle fileShows the pickle opcodes without executing them, which makes it the safer tool for untrusted files.
python -m idlelibStart IDLE
python -m tkinterTest the Tk installationOpens a small demonstration window and shows the installed Tcl/Tk version.
python -m turtledemoOpen the turtle demo viewer

Testing and timing 19

CommandWhat it does
python -m unittestDiscover and run all testsWith no arguments it starts test discovery, exactly like the discover sub-command.
python -m unittest discover -s project_directory -p "*_test.py"Discover tests in a directory-s sets the start directory and -p the file pattern, which is test*.py by default.
python -m unittest test_module1 test_module2Run named test modules
python -m unittest test_module.TestClassRun one test class
python -m unittest test_module.TestClass.test_methodRun a single test method
python -m unittest tests/test_something.pyRun tests by file pathConvenient with shell completion; the file must still be importable as a module.
python -m unittest -v test_moduleRun tests with verbose output
python -m unittest -fStop at the first failure
python -m unittest -bBuffer output of passing testsstdout and stderr are captured and shown only for a test that fails or errors.
python -m unittest -k PATTERNRun tests matching a patternSelects test methods and classes by substring or wildcard; repeatable.
python -m unittest -hList unittest options
python -m doctest -v example.pyRun a module's doctestsImports the file as a standalone module and prints a detailed report of every example tried.
python -m timeit "'-'.join(str(n) for n in range(100))"Time a one-line statementThe loop count is chosen automatically and the best of five repeats is reported.
python -m timeit -s "text = 'sample string'; char = 'g'" "char in text"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 STATEMENTSet the loop countFixes how many times the statement runs in each measurement.
python -m timeit -r N STATEMENTSet the number of repeatsFive measurements are taken by default.
python -m timeit -u U STATEMENTChoose the output time unitU is one of nsec, usec, msec or sec.
python -m timeit -p STATEMENTMeasure process timeSwitches from the wall-clock timer time.perf_counter() to time.process_time().
python -m trace --count -C . somefile.pyWrite line-count coverage listingsRuns the script and puts annotated listings of every imported module in the current directory.

Debugging and profiling 13

CommandWhat it does
python -m pdb PYFILEDebug a scriptPauses before the first line and enters post-mortem debugging if the program exits abnormally.
python -m pdb -c COMMAND PYFILERun debugger commands at startEach -c command is executed as if it came from a .pdbrc file.
python -m pdb -m MODULEDebug a moduleFinds the module the way python -m does and pauses before its first line.
python -m pdb -p 1234Attach to a running processThe number is the process ID; attaching to a live process is new in 3.14.
python -m cProfile myscript.pyProfile a scriptPrints call counts and timings for every function when the script ends.
python -m cProfile -o OUTPUT_FILE myscript.pySave profile data to a fileThe saved results are read back later with the pstats.Stats class.
python -m cProfile -s SORT_ORDER myscript.pySort the profile reportTakes a sort_stats() key and applies only when -o is not used.
python -m cProfile -m MODULEProfile 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.txtRun 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.rstFind where a leaked file was openedWith tracemalloc enabled the warning includes the traceback of the allocation.
python -m asyncio ps PIDList tasks of a running processReads the task state of the other process without executing any code in it.
python -m asyncio pstree PIDShow the task tree of a process

Windows py command 9

CommandWhat it does
pyLaunch the default runtimeBehaves like python by default and can replace it in any command.
py -V:3.14Launch a specific versionThe tag option has to come first; official releases can also be written without the V: part.
py listList installed runtimesTags can be added as filters, and --one prints just the runtime that would be launched.
py list --online 3.14List installable runtimesSearches the online index for versions that py install could add.
py install TAGInstall a runtimeSeveral tags may be given; the special tag default selects the default runtime.
py install --updateUpdate installed runtimesWithout tags, every runtime the install manager manages is replaced when a newer version exists.
py uninstall TAGRemove a runtimeAsks for confirmation unless --yes is passed.
py uninstall --purgeRemove all managed runtimesAlso cleans up the Start menu, the registry and any download caches.
py helpShow install manager commandspy help install, or -? after a command, prints the help of one subcommand.

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__)".

Sources and checks

53 more source pages

Every row on this page was matched to a line in the documentation above on . A binding that could not be found there is not listed.

Found a wrong or missing key? Tell us and it gets checked against the source. How we verify describes the process and its limits.