PYnative

Practice Coding

  • Python â–¼
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Coding Exercises â–¼
    • Python Exercises
    • C++ Exercises
    • C Programming Exercises
    • Java Exercises
    • C# Exercises
  • MCQsâ–¼
    • Python MCQ Quizzes
    • Java MCQ Quizzes
    • C++ MCQ Quizzes
  • Compilersâ–¼
    • Online Python Compiler
    • Online C Compiler
    • Online C++ Compiler
    • Online Java Compiler
    • Online C# Compiler
Home » Python » Basics » Running Python Scripts From the Command Line

Running Python Scripts From the Command Line

Updated on: December 4, 2026 | Leave a Comment

Once you’ve saved Python code in a .py file, you need a way to run it. Code editors have a Run button, but every Python programmer should also know how to run a script from the command line (the terminal). It works the same way on every computer, it’s how programs run on servers, and it lets you do things a Run button can’t, such as pass extra information to your script.

In this tutorial, you’ll learn how to move to your script’s folder, run the script, give it input and arguments, stop it, and fix the errors beginners hit most often. Each step covers Windows, macOS, and Linux.

Key terms used in this article:

  • Command line (or terminal): A text window where you type commands. On Windows it’s Terminal, PowerShell, or Command Prompt. On macOS and Linux it’s Terminal.
  • Script: A file of Python code ending in .py.
  • Current folder (or working directory): The folder your terminal is “in” right now. Commands look for files here first.
  • Path: The location of a file or folder, such as C:\Users\Jessa\python_projects\hello.py.
  • Argument: Extra information you type after a command, such as a file name or a number.

Table of contents

  • Before you begin
  • Step 1: Open a terminal
  • Step 2: Go to your script’s folder
  • Step 3: Run the script
  • Run a script from a different folder
  • Scripts that ask for input
  • Pass arguments to a script
  • Stop a running script
  • Useful python command options
  • Save a script’s output to a file
  • Common errors and how to fix them
  • Optional extras
    • Run a script directly on macOS and Linux
    • Build a friendlier command with argparse
  • Practice exercises
  • Summary

Before you begin

You need Python installed. If you haven’t installed it yet, follow How to Install Python on Windows, macOS, and Linux.

Then create a folder named python_projects in your home folder (for example, C:\Users\Jessa on Windows or /Users/jessa on macOS). Inside it, save a file named hello.py with this code:

print("Hello, World!")
print("This script runs from the command line.")Code language: Python (python)

If you haven’t written a script before, start with Your First Python Program: Hello World Explained.

Step 1: Open a terminal

  • Windows: Press the Windows key, type Terminal (or PowerShell), and press Enter.
  • macOS: Press Cmd + Space, type Terminal, and press Enter.
  • Linux: Press Ctrl + Alt + T on most distributions.
  • VS Code or PyCharm: Open the built-in terminal (View › Terminal in VS Code, or the Terminal tool window in PyCharm). It usually starts in your project folder already.

The terminal shows a prompt and waits for a command. It usually includes the current folder, for example PS C:\Users\Jessa> on Windows or jessa@MacBook ~ % on macOS.

Step 2: Go to your script’s folder

The terminal is always “in” a folder, called the current folder. When you run python hello.py, Python looks for hello.py in the current folder. So first, move into the folder that contains your script with the cd (“change directory”) command:

cd python_projectsCode language: Python (python)

Then check that your script is there by listing the files in the folder:

# Windows (Command Prompt) - PowerShell also accepts ls
dir

# macOS and Linux
lsCode language: Python (python)

These are the folder commands you’ll use most:

TaskWindowsmacOS and Linux
Show the current foldercd (Command Prompt) or pwd (PowerShell)pwd
List files in the current folderdirls
Go into a foldercd folder_namecd folder_name
Go up one foldercd ..cd ..
Go to your home foldercd ~ (PowerShell) or cd %USERPROFILE%cd ~

Tip: Typing long folder names is slow. Type cd (with a space), then drag the folder from File Explorer or Finder into the terminal window. Its full path appears automatically. Press Enter.

Step 3: Run the script

Type python, a space, and the name of your script:

# Windows
python hello.py

# macOS and Linux
python3 hello.pyCode language: Python (python)

Output:

Hello, World!
This script runs from the command line.

Python reads the file, runs every line from top to bottom, and then returns you to the terminal prompt. You can run it again as often as you like. Press the Up arrow to bring back the last command instead of retyping it.

Which command should I use? On Windows, use python, or py if you installed Python with the Python install manager. On macOS and Linux, use python3. Inside an activated virtual environment, python works everywhere. In the rest of this article, examples use python, so type python3 on macOS and Linux if needed.

Run a script from a different folder

You don’t have to cd into the script’s folder. You can give Python the script’s path instead.

  • A relative path starts from the current folder: python python_projects/hello.py
  • An absolute path (or full path) starts from the top of the drive and works from anywhere:
    python C:\Users\Jessa\python_projects\hello.py (Windows)
    python3 /Users/jessa/python_projects/hello.py (macOS)

If a folder or file name contains spaces, wrap the whole path in quotation marks. Otherwise, the terminal treats each word as a separate item:

python "my scripts/hi.py"Code language: Python (python)

To avoid this problem, use underscores instead of spaces in folder and file names, such as my_scripts.

Scripts that ask for input

When a script uses input(), it pauses and waits for you to type an answer in the terminal and press Enter. Save this as greet.py:

name = input("What is your name? ")
print(f"Nice to meet you, {name}!")Code language: Python (python)

Run it with python greet.py:

What is your name? Jessa
Nice to meet you, Jessa!

If your script seems to “freeze” with no output, check whether it’s waiting for input.

Pass arguments to a script

Instead of asking questions while the script runs, you can give it information up front by typing arguments after the script name. Python stores them in a list called sys.argv (“argument values”). Save this as show_args.py:

import sys

print("Script name:", sys.argv[0])
print("Arguments:", sys.argv[1:])Code language: Python (python)

Run it with three arguments:

python show_args.py Jessa 25 "New York"Code language: Python (python)

Output:

Script name: show_args.py
Arguments: ['Jessa', '25', 'New York']

Things to notice:

  • sys.argv[0] is always the script’s name. Your arguments start at sys.argv[1].
  • Arguments are separated by spaces. Put quotes around an argument that contains a space, such as "New York".
  • Every argument arrives as text (a string), even 25. Convert it with int() or float() if you need a number.

Example: add two numbers from the command line

import sys

# Make sure exactly two numbers were given
if len(sys.argv) != 3:
    print("Usage: python add_numbers.py NUMBER1 NUMBER2")
    sys.exit(1)

a = int(sys.argv[1])
b = int(sys.argv[2])
print(f"{a} + {b} = {a + b}")Code language: Python (python)

Save it as add_numbers.py and run it:

> python add_numbers.py 10 20
10 + 20 = 30

> python add_numbers.py 10
Usage: python add_numbers.py NUMBER1 NUMBER2

The if check prints a helpful message when the wrong number of arguments is given, and sys.exit(1) stops the script there.

Stop a running script

Most scripts finish on their own. But sometimes a script runs much longer than expected, for example because of a loop that never ends. Here’s a script that counts forever on purpose:

import time

count = 0
while True:
    count += 1
    print("Counting:", count)
    time.sleep(1)  # wait 1 secondCode language: Python (python)

To stop it, click in the terminal and press Ctrl + C (on every operating system, including macOS). Python stops the script and shows a KeyboardInterrupt message:

Counting: 1
Counting: 2
Counting: 3
^CTraceback (most recent call last):
  File "count.py", line 7, in <module>
    time.sleep(1)  # wait 1 second
    ~~~~~~~~~~^^^
KeyboardInterrupt

This message isn’t a bug in your code. It just confirms that you stopped the script yourself.

Useful python command options

The python command accepts options (also called flags) that start with a dash. Here are the ones beginners use most:

CommandWhat it does
python --versionShows the installed Python version
pythonOpens the interactive shell instead of running a file
python -i script.pyRuns the script, then opens the interactive shell so you can inspect its variables
python -c "print(2 ** 10)"Runs one short piece of code without a file
python -m module_nameRuns a module that comes with Python, or one you installed
python -hLists all options

Try the -m option: Python comes with many ready-to-run modules. For example, the built-in calendar module prints a calendar for any month:

python -m calendar 2026 12Code language: Python (python)

Output:

   December 2026
Mo Tu We Th Fr Sa Su
    1  2  3  4  5  6
 7  8  9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31

You’ll use -m often later, for example python -m venv .venv to create a virtual environment and python -m pip install requests to install a package.

Save a script’s output to a file

Add > and a file name after the command to send everything the script prints into a file instead of the screen. This works on Windows, macOS, and Linux:

# Save the output to output.txt (replaces the file if it exists)
python hello.py > output.txt

# Add the output to the end of output.txt
python hello.py >> output.txtCode language: Python (python)

Nothing appears on the screen, because the output went into output.txt. Open the file to see it. Error messages still appear on the screen.

Common errors and how to fix them

1. “can’t open file … No such file or directory”

python: can't open file 'C:\\Users\\Jessa\\helo.py': [Errno 2] No such file or directory

Python can’t find the file. Either the name is misspelled, or the terminal is in a different folder. Run dir (Windows) or ls (macOS and Linux) to see which files are in the current folder, and cd into the right folder. Also check the extension. Windows sometimes hides it, so a file you think is hello.py may actually be hello.py.txt.

2. “python is not recognized” or “command not found”

The terminal can’t find Python. On macOS and Linux, use python3. On Windows, try py, close and reopen the terminal, or check that Python was added to your PATH during installation. See the troubleshooting section of How to Install Python.

3. SyntaxError: invalid syntax on the python hello.py command itself

>>> python hello.py
  File "<stdin>", line 1
    python hello.py
           ^^^^^
SyntaxError: invalid syntax

You typed the command inside the Python shell (notice the >>> prompt). Type exit() to return to the terminal, then run the command again.

4. ModuleNotFoundError: No module named ...

Your script imports a package that isn’t installed for the Python you’re using. Install it with python -m pip install package_name, using the same python command you use to run the script. If you use a virtual environment, activate it first.

5. The window opens and closes immediately (Windows)

If you double-click a .py file in File Explorer, Windows may open a console window, run the script, and close the window as soon as the script ends, before you can read anything. Run the script from a terminal instead, as shown in this article, so the output stays on screen.

Optional extras

You can skip this section for now. Come back to it when you want your scripts to behave more like real command-line tools.

Run a script directly on macOS and Linux

On macOS and Linux, you can run a script without typing python3 in front of it. Add this special first line, called a shebang, which tells the system to use Python:

#!/usr/bin/env python3
print("Hello from an executable script!")Code language: Python (python)

Save it as hello_exec.py, give it permission to run once with chmod, and then run it with ./ in front of its name:

chmod +x hello_exec.py
./hello_exec.pyCode language: Python (python)

Output:

Hello from an executable script!

On Windows, the shebang line is simply treated as a comment, so the script still works with python hello_exec.py.

Build a friendlier command with argparse

sys.argv is fine for simple scripts. For anything bigger, the built-in argparse module checks arguments for you, converts types, and creates a help message automatically. Save this as greet_cli.py:

import argparse

parser = argparse.ArgumentParser(description="Greet someone.")
parser.add_argument("name", help="the person to greet")
parser.add_argument("--times", type=int, default=1, help="how many times to greet")
args = parser.parse_args()

for _ in range(args.times):
    print(f"Hello, {args.name}!")Code language: Python (python)
> python greet_cli.py Jessa --times 2
Hello, Jessa!
Hello, Jessa!

> python greet_cli.py -h
usage: greet_cli.py [-h] [--times TIMES] name

Greet someone.

positional arguments:
  name           the person to greet

options:
  -h, --help     show this help message and exit
  --times TIMES  how many times to greet

Practice exercises

Exercise 1: Create a script named today.py that prints today’s date, and run it from the command line.

# Solution: today.py
from datetime import date

print("Today is", date.today())

# Run it with: python today.pyCode language: Python (python)

Exercise 2: Write a script named shout.py that takes a word as an argument and prints it in capital letters. For example, python shout.py hello prints HELLO.

# Solution: shout.py
import sys

word = sys.argv[1]
print(word.upper())Code language: Python (python)

Exercise 3: Write a script named rectangle.py that takes a width and a height as arguments and prints the area. For example, python rectangle.py 4 5 prints Area: 20.

# Solution: rectangle.py
import sys

width = float(sys.argv[1])
height = float(sys.argv[2])
print(f"Area: {width * height:g}")Code language: Python (python)

Summary

  • Open a terminal, use cd to go to your script’s folder, and run it with python script.py (python3 on macOS and Linux, or py on Windows with the install manager).
  • Use dir (Windows) or ls (macOS and Linux) to check that the script is in the current folder.
  • You can also run a script from anywhere by giving its full path. Put quotes around paths that contain spaces.
  • Scripts that use input() wait for you to type in the terminal.
  • Arguments typed after the script name are available in sys.argv, always as text. sys.argv[0] is the script name.
  • Press Ctrl + C to stop a running script.
  • Useful options include --version, -i, -c, and -m. Use > to save output to a file.
  • Most errors come from being in the wrong folder, a misspelled file name, using the wrong Python command, or typing the command inside the Python shell.

Also, See:

  • Using the Python Interactive Shell (REPL)
  • Python Input: Take Input from User
  • Basic Python exercise for beginners

Filed Under: Python, Python Basics

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python Basics

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises
Java Exercises
C# Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: Python Python Basics
TweetF  sharein  shareP  Pin

  Python Tutorials

  • Get Started with Python
  • Python Statements
  • Python Comments
  • Python Keywords
  • Python Variables
  • Python Operators
  • Python Data Types
  • Python Casting
  • Python Control Flow statements
  • Python For Loop
  • Python While Loop
  • Python Break and Continue
  • Python Nested Loops
  • Python Input and Output
  • Python range function
  • Check user input is String or Number
  • Accept List as a input from user
  • Python Numbers
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python Functions
  • Python Modules
  • Python isinstance()
  • Python OOP
  • Python Inheritance
  • Python Exceptions
  • Python Exercise for Beginners
  • Python Quiz for Beginners

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

  • Python Basics
  • Python Exercises
  • Python Quizzes
  • Python File Handling
  • Python Date and Time
  • Python OOP
  • Python Random
  • Python Regex
  • Python Pandas
  • Python Databases
  • Python MySQL
  • Python PostgreSQL
  • Python SQLite
  • Python JSON

About PYnative

PYnative.com is a platform built to help developers learn by doing. Solve coding exercises, take MCQs, and run code directly in built-in online compilers.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises
  • Java Exercises
  • C# Exercises

MCQ Quizzes

  • Python MCQs
  • Java MCQs
  • C++ MCQs

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com