How to Run a Python Script from the Command Line

Short answer
Save your code in a file such as hello.py, open a terminal in that folder and run python hello.py (or python3 hello.py on macOS and Linux, py hello.py on Windows).

A Python script is a plain text file with the extension .py. When you run it, Python reads the file from top to bottom and executes each statement. You can run scripts from a terminal, from an editor such as VS Code or IDLE, or double-click them on some systems, but the terminal is the most reliable and is what servers and automation use.

This page shows the commands, how to pass arguments, and how if __name__ == "__main__": lets a file work both as a script and as an importable module.

Quick facts
Run a scriptpython script.py
macOS / Linuxpython3 script.py
Windows launcherpy script.py
Run a modulepython -m package.module
ArgumentsRead from sys.argv

Run a Python script step by step

  1. Save your code, for example as hello.py.
  2. Open a terminal and change to the folder that holds the file with cd.
  3. Run the file with the command for your system.
  4. If you installed packages into a virtual environment, activate it first.

If the terminal says can't open file, you are in the wrong folder or mistyped the name; use ls (macOS, Linux) or dir (Windows) to see what is there.

# go to the folder
cd path/to/my_project

# run the script
python hello.py          # most systems
python3 hello.py         # macOS / Linux if python is not found
py hello.py              # Windows launcher

# run with arguments
python greet.py Asha 3

Pass command-line arguments with sys.argv

Everything you type after the script name arrives in the list sys.argv as strings. sys.argv[0] is the script's name, so your own arguments start at index 1. Convert numbers with int() yourself; see type casting.

The snippet below parses a pretend argument list so the output is fixed:

Python
argv = ["greet.py", "Asha", "3"]
name = argv[1]
times = int(argv[2])
print(("Hello " + name + "! ") * times)

Use if __name__ == "__main__" to separate script and module code

When a file is run directly, Python sets its __name__ to "__main__". When another file imports it, __name__ is the module's own name instead. Wrapping the start-up code in this check means it runs only when you execute the file, not when you import it, which is essential for testing and reuse.

Python
def main():
    print("running as a script")

if __name__ == "__main__":
    main()

Other ways to run Python code

WayCommand or actionGood for
Terminalpython script.pyEveryday use, automation, servers
Interactive promptpython then type codeQuick experiments
One-linerpython -c "print(2 + 2)"Tiny checks in a shell
Modulepython -m http.serverRunning standard tools and packages
EditorRun button in VS Code, PyCharm or IDLEDevelopment with debugging
Executable script (Linux, macOS)#!/usr/bin/env python3 then chmod +x script.pyRunning as ./script.py

Examples you can run

Press Run, then edit the code and run it again.

Check how the file is being run

Run directly, __name__ is "__main__", so the guarded code executes.

Check how the file is being run
def main():
    print("started")

print(__name__ == "__main__")
if __name__ == "__main__":
    main()
Expected outputTrue
started

Read arguments like sys.argv

sys.argv is a list of strings with the script name first. A fixed list stands in here.

Read arguments like sys.argv
argv = ["total.py", "4", "6", "10"]
numbers = [int(a) for a in argv[1:]]
print("script:", argv[0])
print("sum:", sum(numbers))
Expected outputscript: total.py
sum: 20

sys.argv always has at least the script name

Even with no arguments, sys.argv holds one item, so index 0 is always safe.

sys.argv always has at least the script name
import sys

print(isinstance(sys.argv, list))
print(len(sys.argv) >= 1)
Expected outputTrue
True

Ask for input when a script runs

Interactive scripts read from the keyboard; the sample input is supplied as stdin.

Ask for input when a script runs
name = input("Name: ")
print("Hello,", name)
Expected outputName: Asha
Hello, Asha

Common mistakes

Running the command from the wrong folder

✗ Wrong

python hello.py
python: can't open file 'hello.py': [Errno 2] No such file or directory

✓ Right

cd path/to/my_project
python hello.py

Use cd to move into the folder containing the file, or give the full path, for example python path/to/hello.py.

Typing the script name inside the Python prompt

✗ Wrong

>>> python hello.py
SyntaxError: invalid syntax

✓ Right

python hello.py

python hello.py is a terminal command. Leave the >>> prompt with exit() and type it in the terminal.

Forgetting to convert command-line arguments

✗ Wrong

import sys
total = sys.argv[1] + sys.argv[2]
print(total)
Running `python add.py 2 3` prints 23, because the arguments are strings.

✓ Right

import sys
total = int(sys.argv[1]) + int(sys.argv[2])
print(total)

sys.argv items are always strings. Convert with int() or float() before doing math.

How to Run a Python Script from the Command Line: questions people ask

How do I run a Python file in the terminal?

Open a terminal in the file's folder and type python filename.py. Use python3 on macOS and Linux if python is not found, or py on Windows.

What does if __name__ == "__main__" do?

It runs the code beneath it only when the file is executed directly, not when it is imported by another file. Python sets __name__ to "__main__" for the directly run file.

Why does 'python' say command not found?

Python is not installed or not on your PATH, or your system only provides python3. Try python3 --version or py --version and use whichever works.

Keep learning

Step-by-step lessons:
What Is Python?Python SyntaxPython Modules and Imports

Related:
How to Install a Package with pip in PythonHow to Create a Virtual Environment in PythonPython input() FunctionPython Module vs Package: What Is the Difference?

More in setup and tooling:
How to Install a Package with pip in PythonHow to Create a Virtual Environment in Python See all →