Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.
Python commands depend on where you type them. Terminal commands launch Python, run scripts, create virtual environments, and manage packages. Python expressions and statements run inside the Python REPL or a .py file. This cheat sheet separates those contexts and includes macOS/Linux, Windows Command Prompt, and PowerShell examples.
Examples target modern Python 3. As of August 18, 2026, the official documentation covers Python 3.14.6, released June 10, 2026. Executable names, shell quoting, package availability, and some options can vary by operating system, shell, installation method, and Python version.
Quick-reference Python commands
| Task | macOS/Linux | Windows |
|---|---|---|
| Check Python | python3 --version |
py --version |
| Start the REPL | python3 |
py |
| Run a file | python3 script.py |
py script.py |
| Create an environment | python3 -m venv .venv |
py -m venv .venv |
| Install a package | python3 -m pip install package |
py -m pip install package |
| List packages | python3 -m pip list |
py -m pip list |
Once a virtual environment is activated, use python and python -m pip so both commands refer to that environment.
1. Terminal commands for Python
Check whether Python is installed
python --version
python3 --version
On Windows, also try the Python launcher:
py --version
To display detailed interpreter information:
python -c "import sys; print(sys.version)"
To find the executable selected by your shell:
# macOS/Linux
which python
which python3
# Windows
where python
where py
python, python3, and py are not interchangeable on every computer. python may point to Python 3, another installation, or nothing at all. python3 is common on Unix-like systems, while py is the Windows Python launcher and can select a particular installed version.
Start and exit the Python REPL
The interactive interpreter, commonly called the REPL, lets you enter Python one line at a time:
# macOS/Linux
python3
# Windows
py
Inside the REPL, exit with:
exit()
quit()
Keyboard alternatives are Ctrl-D on macOS/Linux and Ctrl-Z followed by Enter on Windows. These are terminal control sequences, not Python statements. See the official command-line documentation.
Run a Python file
python script.py
python3 script.py
py script.py
Use the form that matches your installation. Pass command-line arguments after the filename:
Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Repair Windows errors before they cause bigger problemsFix Now →python script.py first second
Read them in Python with:
import sys
print(sys.argv)
Run a module with -m
python -m module_name
python -m package.module
-m asks the selected interpreter to locate and run a module. This is especially useful for package-aware execution and for built-in tools such as pip, unittest, and http.server.
Execute a short command with -c
python -c "print('Hello, Python')"
python -c "import sys; print(sys.version)"
python -c "import os; print(os.getcwd())"
python -c "from pathlib import Path; print(Path.cwd())"
Quoting rules differ between Bash, zsh, PowerShell, and Command Prompt, so a command copied from another operating system may need adjustment.
Run code from standard input
echo "print('Hello')" | python
printf "print(2 + 2)n" | python
This is mainly useful in Unix-style shell pipelines and is less important for beginners.
Useful interpreter options
| Command | Purpose |
|---|---|
python --help |
Show interpreter help |
python --version |
Show the Python version |
python -c "..." |
Execute a short command |
python -m module |
Run a module as a script |
python -i script.py |
Run a script, then stay interactive |
python -B script.py |
Do not write bytecode files |
python -u script.py |
Use unbuffered standard output and error |
python -O script.py |
Enable basic optimization mode |
python -X ... |
Select implementation-specific options |
python -W ... |
Configure warning behavior |
The last five options are operational tools rather than everyday beginner commands. Options can change between Python versions; consult the version-specific command-line reference.
Free tools Windows power users keep installed
One-click scans. No signup required.
2. Virtual-environment commands
A virtual environment isolates a project’s packages from other projects and from the operating system’s Python installation. Python’s built-in venv module is the standard-library choice for modern Python 3 projects.
Create an environment
# macOS/Linux
mkdir my-project
cd my-project
python3 -m venv .venv
# Windows PowerShell
mkdir my-project
cd my-project
py -m venv .venv
.venv is a conventional project-local directory name. Add it to Git’s ignore file:
.venv/
Activate it
# macOS/Linux with Bash or zsh
source .venv/bin/activate
# Windows Command Prompt
.venvScriptsactivate
# Windows PowerShell
.venvScriptsActivate.ps1
Fish, csh, and other shells use different activation scripts. Activation changes the current shell’s PATH; it is convenient but not required. You can call the environment’s interpreter directly:
# macOS/Linux
.venv/bin/python app.py
.venv/bin/python -m pip install requests
# Windows PowerShell
.venvScriptspython.exe app.py
.venvScriptspython.exe -m pip install requests
Verify the active interpreter
# macOS/Linux
which python
python -c "import sys; print(sys.executable)"
# Windows
where python
python -c "import sys; print(sys.executable)"
The path should contain .venv/bin/python on Unix-like systems or .venvScriptspython.exe on Windows.
Recommended Free Tools
Deactivate, reactivate, or recreate
deactivate
To use the environment again in a new terminal, activate it again. If an environment is corrupted, deactivate it, remove the .venv directory, and recreate it with python -m venv .venv. Do not delete it while its interpreter is running.
3. pip package commands
The safest general pattern is:
python -m pip install package
This binds pip to the interpreter selected by python. On systems where Python 3 is named separately, use python3 -m pip; on Windows, py -m pip or a version-specific launcher such as py -3.14 -m pip.
Install and upgrade packages
python -m pip install requests
python -m pip install requests flask pandas
python -m pip install requests==2.32.4
python -m pip install "requests>=2.32"
python -m pip install --upgrade requests
Quote version constraints because shells can interpret characters such as > and <.
Install from a requirements file
python -m pip install -r requirements.txt
Inspect installed packages
python -m pip list
python -m pip show requests
python -m pip freeze
python -m pip check
python -m pip inspect
listdisplays installed packages.showdisplays metadata and installation details for one package.freezeprints installed distributions and versions.checkreports incompatible dependency requirements.inspectproduces environment metadata for deeper inspection.
Uninstall packages and upgrade pip
python -m pip uninstall requests
python -m pip install --upgrade pip
Do not upgrade every package indiscriminately: newer versions can introduce incompatibilities. For a project, define and review dependency constraints deliberately.
Do these 3 things before closing this tab:
1Scan for outdated or missing drivers - takes under a minute2Repair Windows errors before they cause bigger problems3Fix the driver behind crashes, sound loss and screen glitchesCreate a requirements snapshot
python -m pip freeze > requirements.txt
python -m pip install -r requirements.txt
pip freeze records what is installed in the current environment. It can include transitive dependencies and unrelated packages, so it is a useful snapshot but not always an ideal direct-dependency manifest. Platform-specific dependencies may also require different specifications.
Less frequent pip commands
python -m pip cache info
python -m pip config list
python -m pip debug
These help inspect pip’s cache, configuration, and environment. The pip command reference contains the current command inventory. Older guides may recommend pip search; do not treat it as a universally reliable discovery workflow. Direct package indexes and project documentation are generally better starting points.
4. When pip is missing or installs into the wrong place
If pip is unavailable, try:
python -m ensurepip --default-pip
python -m pip --version
This is not the correct fix for every operating-system-managed Python installation. Some Linux distributions package Python and pip components separately. Prefer a virtual environment or the distribution’s package manager, and do not use sudo pip install ... as a universal solution.
When a script reports ModuleNotFoundError after a successful installation, compare the interpreter and pip paths:
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
python -c "import sys; print(sys.executable)"
python -m pip --version
Both should refer to the same installation or virtual environment. Also remember that a package’s pip distribution name and its Python import name are not guaranteed to match.
5. Python REPL commands and inspection
The following are Python functions, not terminal commands. Type them after starting the REPL or place them in a .py file:
import math
help()
help(math)
help(math.sqrt)
dir(math)
exit()
quit()
help() opens Python’s built-in documentation system. dir() lists attributes available on an object or module.
To see where an installed module came from:
import requests
print(requests.__file__)
6. Essential Python built-ins
| Function | Example | Purpose |
|---|---|---|
print() |
print("Hi") |
Display output |
input() |
name = input("Name: ") |
Read text input |
len() |
len(items) |
Count items |
type() |
type(value) |
Get an object’s type |
isinstance() |
isinstance(x, int) |
Test type membership |
int() |
int("42") |
Convert to an integer |
float() |
float("3.14") |
Convert to floating point |
str() |
str(42) |
Convert to a string |
list() |
list(range(3)) |
Create a list |
dict() |
dict(a=1) |
Create a dictionary |
set() |
set(values) |
Create a set |
range() |
range(5) |
Represent an integer sequence |
enumerate() |
enumerate(items) |
Add indexes during iteration |
zip() |
zip(names, scores) |
Iterate over sequences together |
sorted() |
sorted(items) |
Return sorted data |
sum() |
sum(numbers) |
Add numeric values |
min(), max() |
max(scores) |
Find extreme values |
abs() |
abs(-4) |
Return absolute value |
round() |
round(3.14159, 2) |
Round a number |
open() |
open("data.txt") |
Open a file |
help(), dir() |
help(str) |
Read documentation or inspect attributes |
See the Python built-in function reference for version-specific behavior.
Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchWindows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstall7. Python language constructs
if, for, while, def, and class are Python language constructs, not commands typed directly into your operating-system shell.
Variables and comments
name = "Ada"
count = 3
# This is a comment
Conditionals and loops
if score >= 60:
print("Pass")
else:
print("Try again")
for item in items:
print(item)
while count > 0:
count -= 1
Functions and exceptions
def greet(name):
return f"Hello, {name}"
try:
value = int(user_input)
except ValueError:
print("Enter a whole number")
Context managers and comprehensions
with open("data.txt", encoding="utf-8") as file:
text = file.read()
squares = [n * n for n in range(10)]
8. Files and directories with pathlib
pathlib is the preferred modern standard-library interface for many path operations:
from pathlib import Path
path = Path("data.txt")
print(path.exists())
print(path.name)
print(path.suffix)
text = Path("input.txt").read_text(encoding="utf-8")
Path("output.txt").write_text("Donen", encoding="utf-8")
for path in Path(".").iterdir():
print(path)
Older code often uses os.path; it remains valid, but new code can usually use pathlib for clearer path handling.
9. Validation, testing, and standard-library tools
Check syntax without running a file
python -m py_compile script.py
python -m compileall .
The first command compiles one file. The second searches a directory tree for Python files to compile.
Run tests
python -m unittest
unittest is included in Python’s standard library. pytest is third-party:
python -m pip install pytest
python -m pytest
Start a local web server
python -m http.server
python -m http.server 8000
This serves the current directory for local testing. Do not expose it to an untrusted network or use it as a production web server.
Use built-in modules from the terminal
python -m json.tool data.json
python -m zipfile -l archive.zip
python -m http.server 8000
python -m calendar
These examples demonstrate the general python -m module mechanism: a module can provide a command-line interface even when it is primarily a Python library.
10. Run a script as an executable
On Unix-like systems, add a shebang at the top of the file:
#!/usr/bin/env python3
Then make it executable and run it:
chmod +x script.py
./script.py
This depends on file permissions, the shell, and the installed interpreter. Windows generally uses file associations or an explicit command such as py script.py.
11. A practical project workflow
macOS/Linux
mkdir my-project
cd my-project
python3 -m venv .venv
source .venv/bin/activate
python -m pip install --upgrade pip
python -m pip install requests
python -m pip freeze > requirements.txt
python app.py
deactivate
Windows PowerShell
mkdir my-project
cd my-project
py -m venv .venv
.venvScriptsActivate.ps1
python -m pip install --upgrade pip
python -m pip install requests
python -m pip freeze > requirements.txt
python app.py
deactivate
Upgrading pip is a common maintenance step, not a mandatory prerequisite before every installation.
12. Troubleshooting common errors
“python is not recognized” or “command not found”
Try the alternative executable name:
python3 --version
py --version
If none works, install Python through an appropriate official or operating-system channel and ensure the executable is available to your shell. The Python downloads page provides official installers, although some organizations require an approved distribution channel.
PowerShell blocks activation
Rather than casually changing a machine-wide execution policy, bypass activation and call the environment directly:
.venvScriptspython.exe app.py
.venvScriptspython.exe -m pip install requests
“No module named venv”
Some operating-system distributions package the venv component separately. Install the matching package through that distribution’s package manager, then retry python3 -m venv .venv. There is no single package name that applies to every Linux distribution.
“No module named pip”
Try python -m ensurepip --default-pip, but check your operating system’s Python packaging policy first. A virtual environment or distribution-specific package may be the appropriate solution.
pip and Python use different installations
Do not switch randomly between pip, pip3, and multiple Python commands. Use:
python -c "import sys; print(sys.executable)"
python -m pip --version
Then install with that same interpreter.
Permission errors
Install inside a virtual environment. A per-user installation may be appropriate in some cases:
The Tool Desk
Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →python -m pip install --user package
--user is not a replacement for a virtual environment in every situation, and some managed environments prohibit user-site installation. Avoid treating sudo pip install as the default repair.
The script works in an IDE but not the terminal
The IDE may use a different interpreter. Compare its selected interpreter with:
python -c "import sys; print(sys.executable)"
Also check the IDE’s project interpreter and the terminal’s virtual-environment state. Opening an integrated terminal does not guarantee that the project environment is selected.
Printable condensed reference
| Need to | Command |
|---|---|
| Check version | python --version |
| Locate interpreter | python -c "import sys; print(sys.executable)" |
| Run a file | python script.py |
| Run a module | python -m module |
| Run a one-liner | python -c "..." |
| Create venv | python -m venv .venv |
| Activate POSIX | source .venv/bin/activate |
| Activate Windows CMD | .venvScriptsactivate |
| Activate PowerShell | .venvScriptsActivate.ps1 |
| Install package | python -m pip install package |
| Install requirements | python -m pip install -r requirements.txt |
| List packages | python -m pip list |
| Check dependencies | python -m pip check |
| Export snapshot | python -m pip freeze > requirements.txt |
| Compile-check | python -m py_compile script.py |
| Run tests | python -m unittest |
| Serve local files | python -m http.server 8000 |
| Leave venv or REPL | deactivate or exit() |
For the complete, current syntax and option details, use the official Python 3 documentation, the Python installation guide, and the Python Packaging User Guide.
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Clear out junk files and repair common Windows errors3Scan for outdated or missing drivers - takes under a minuteQuick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

