How to Run a Python Script

Last updated by Dipen Dadhaniya on Mar 28, 2026 at 11:09 PM

Article written by Kuldeep Pant, under the guidance of Marcelo Lotif Araujo, a Senior Software Developer and an AI Engineer. Reviewed by Mrudang Vora, an Engineering Leader with 15+ years of experience.

| Reading Time: 3 minutes

Figuring out how to run a Python script is that lightbulb moment for every developer. It’s the point where your code stops being a wall of text and starts actually doing something.

Whether you’re trying to automate a boring task, messing around in a notebook, or launching a massive project, knowing the right way to execute your code saves you from a world of command-not-found headaches.

In this guide, we’ll break down the go-to methods for running Python. From the classic terminal and interactive mode to modern IDEs. We’ll also cover the quirks of Windows, macOS, and Linux, so you’re covered regardless of your OS.

Key Takeaways

  • Running a script simply means feeding a .py file to the Python interpreter via your terminal, an IDE, or interactive mode.
  • While python3 script.py is the universal standard, your OS might prefer python or py.
  • Quick tests happen in the REPL (interactive mode), while real work happens in the Command Line or an IDE (like VS Code or PyCharm).
  • Python doesn’t just “read” your text; it compiles it into bytecode for the Python Virtual Machine (PVM) to handle.
  • Once you’ve mastered the basics, you can level up by making scripts executable, passing arguments, and automating runs with batch files.

What Is a Python Script?

how to run a Python script using a hello.py

A Python script is a .py file that contains executable Python code. In simple terms, it is a file you write in a text editor and then run with the Python interpreter to produce output or perform a task.

That is why scripts are the starting point for everything from tiny automation jobs to larger applications. W3Schools uses a hello.py example to show this basic flow, while Python’s own documentation describes a module as a file containing Python definitions and statements.

Python Script vs Python Program vs Python Module

This distinction is worth stating clearly because it helps readers understand how Python code is organized. Python’s documentation defines a module as a file containing Python definitions and statements, and it notes that a script file is code executed as a top-level file.

In practice, a script is usually run directly, a module is usually imported, and a program is the broader application made up of one or more files. That “program” definition is a practical writing convention rather than a strict Python-language term, so it is best framed as an organizational concept.

Term What It Is Use Case Example
Script An executable .py file run directly by Python Quick automation, demos, simple tasks hello.py run from the terminal
Program A complete application, often made of multiple files Larger tools or products A CLI app with several Python files
Module An importable Python file containing definitions and statements Reusable code shared across files math_utils.py imported into another file

How to Run Python Code Interactively?

How to run a Python script interactively in the Python REPL

How to run a Python script interactively is the fastest way to test ideas because you do not need to create a file first. You open the Python shell, type code, and see the result immediately. Python’s interactive mode is called the REPL, and it shows the >>> prompt when it is ready for input.

Running Python in Interactive Mode (REPL)

To start the REPL, open your terminal, type python3, and press Enter. You should then see the >>> prompt, which means Python is waiting for the next command. Type a simple expression such as 2 + 2, press Enter, and Python prints the answer right away.

When you are done, type exit() or use the equivalent quit command for your system. Python’s documentation identifies this as interactive mode, and Real Python notes that this is the built-in REPL used for quick experimentation.

# Start the REPL in terminal:
python3

# Then try a few commands:
>>> 2 + 2
4

>>> print("Hello, World!")
Hello, World!

>>> name = "Python"

>>> name.upper()
'PYTHON'

>>> exit()

When to Use Interactive Mode?

How to run a Python script interactively using the REPL workflow?

Interactive mode is especially useful when you want to move fast and avoid file setup. It works well for:

  • Quick testing
  • Debugging small pieces of code
  • Learning Python syntax
  • Exploring APIs and built-in functions
  • Calculator-style computations

That is exactly why many developers use the REPL before they move on to larger scripts or modules. Real Python describes interactive mode as a good place to test ideas and get immediate feedback, while Python’s docs emphasize the >>> prompt as the sign that the interpreter is ready for the next command.

For readers moving from experimentation to practice, this is also a natural bridge to related learning topics such as Python scripting interview questions.

How to Run a Python Script From the Command Line?

How to run a Python script from the command line is the standard way to execute a .py file. You open a terminal, point Python to the script, and the interpreter runs it right away. Python’s command-line interface supports executing a script from a filesystem path, and any extra values you add after the script name are passed into sys. argv.

Basic Command to Run a Python Script

The simplest way to how do I run a Python file is to use the Python interpreter followed by the file name or full file path. On many systems, Python 3 is the safer choice because Python may point to a different interpreter version, while Python 3 explicitly targets Python 3.

Linode notes that version selection matters when multiple Python installations are present. Most guides simply show python script.py, but beginners often get stuck due to version mismatches.

💡 Pro Tip: Clearly highlight the difference between Python and Python 3, which explicitly states Python 3 upfront, reducing confusion and helping readers run scripts correctly from the start.

Also Read: Python Main Function and Examples with Code

Running a Python Script From a Specific DirectoryHow to run a Python script from a specific directory using cd

If your script is not in the current folder, first change into the correct directory, then run it. The interpreter executes the script from the path you provide, so using the right working directory keeps the command simple and readable.

Running Python Modules With the -m Option

Use python3 -m module_name when you want Python to locate a module on the module path and execute it as a script. This is different from direct file execution because -m works with module names, not .py filenames, and Python runs the module as __main__. That makes -m especially useful for package-based tools and standard-library utilities.

python3 -m http.server

In practice, how do I run a Python program with -m?

You use it when the code is organized as a module or package rather than a standalone file. A direct file run is best for a single script; -m is better when you want Python to resolve the module the same way it would during an import.

Running a Python Script With Command-Line Arguments

You can also how do you run a Python program with arguments by placing them after the script name. Python collects those values in sys. argv, where argv[0] is the script name, and the remaining items are the arguments you passed in. That is the foundation for simple CLI tools and many small automation scripts.

python3 script.py arg1 arg2

# script.py

import sys

print(sys.argv)

This setup is the basic answer to how to execute a program in Python when you need input from the terminal. For anything more structured, you can later build on sys. argv with argparse, which parses command-line values into a cleaner interface.

How to Run a Python Script From an IDE or Code Editor?

For day-to-day Python work, an IDE or code editor makes running a script much easier because you can open the file and launch it with a button or shortcut instead of typing a full terminal command. VS Code, PyCharm, Jupyter, and Colab all support quick execution in slightly different ways.

Running Python Script in VS Code

In VS Code, open your .py file and click the Run Python File in Terminal play button in the top-right of the editor. You can also use Ctrl+F5 or right-click the file and choose Run Python File.

How to run a Python script in VS Code

VS Code’s Python docs show that this runs the script in the terminal with the selected interpreter.

Running Python Script in PyCharm

How to run a Python script in PyCharm using the green Run button and a configured interpreter?

In PyCharm, open the script and use the green Run arrow or press Shift+F10 to launch the current run configuration. JetBrains documents this as the standard way to start a script from the IDE, and you can also run a file from the editor context menu.

Running Python Script in Jupyter Notebook / Google Colab

How to run a Python script in Jupyter Notebook

Jupyter Notebook and Google Colab use cell-based execution instead of a traditional single-file run flow. You type code into a cell and press Shift+Enter to execute that cell and move to the next one; Colab also shows a play icon beside each cell.

This setup is especially useful for data analysis, prototyping, and sharing results because output appears right below the code.

Running Python Script in Text Editors

How to run a Python script from a text editor workflow

In text editors like Sublime Text, Vim, or Notepad++, the usual workflow is to save the file and run it from a terminal or a configured build task. These editors can still be effective for simple scripts, but the run experience depends on how the editor is set up.

How to Run a Python Script in Different Operating Systems?

Python works across all major operating systems, so the core idea of how to run a Python script stays the same, even though the command you use may vary slightly on Windows, macOS, and Linux. The main difference is the terminal app and, on Windows, the launcher you use.

Run Python Script on Windows

On Windows, you can run a script from Command Prompt or PowerShell using either python script.py or py script.py. In many Windows setups, the Py launcher is the default and makes it easier to choose the Python version you want to use. That is especially helpful when you are figuring out how to run a Python file without version conflicts.

python script.py

py script.py

How to run a Python script in Command Prompt using python script.py

Run Python Script on macOS

Running Python script on macOS

On macOS, open Terminal and run the script with python3 script.py. This is the most reliable command on modern Mac systems because python3 clearly points to Python 3, which helps avoid confusion when learning how to start a Python script.

Run Python Script on Linux

Running Python script on Linux

On Linux, the usual command is also python3 script.py in the terminal. Most Linux distributions treat Python 3 as the standard interpreter, so this is typically the simplest answer to how to run a Python program on Linux.

How the Python Interpreter Executes a Script?

When you learn how to run a Python script, it also helps to know what happens behind the scenes. Python does not jump straight from .py source code to output; in CPython, the source is compiled into bytecode, cached as .pyc files, and then executed by the Python Virtual Machine (PVM).

How the Python Interpreter Executes a Script

Python’s execution model describes a script file as a code block, and that block runs inside an execution frame. The key idea is simple: the compiler translates readable Python into an internal instruction form, and the runtime evaluates those instructions step by step.

That is why the same script can be run directly, imported as part of a larger project, or executed with -m, depending on how you want to structure your code.

Python Bytecode and the Python Virtual Machine

Python source code is first compiled into bytecode, which the official glossary describes as the internal representation used by the CPython interpreter. That bytecode is often cached in .pyc files, so the same file can start faster on later runs, and the bytecode is then executed by the virtual machine component of the interpreter.

Python Bytecode and the Python Virtual Machine 

This is a useful distinction to remember in interviews because it shows you understand more than just the command line. For deeper practice on execution flow, import behavior, and runtime details, you can also review the related guide on Advanced Python Interview Questions.

Advanced Ways to Run Python Scripts

Once you know the basics of how to run a Python script, it is useful to learn a few advanced methods that make scripting more flexible in real-world workflows. These techniques help when you want to launch scripts with a double-click, make a file runnable from the terminal, capture output, or troubleshoot common setup issues.

Running Python Script Using a Batch File

On Windows, a batch file can act as a simple launcher for a Python script. This is handy when you want a reusable shortcut without typing the full command every time.

@echo off

python script.py

pause

@echo off keeps the terminal output clean, python script.py runs the file, and pause keeps the window open so you can read the result.

Making a Python Script Executable

On macOS and Linux, you can make a script executable so it runs directly from the terminal. First, add a shebang line at the top of the file so the system knows which interpreter to use.

#!/usr/bin/env python3
print("Hello from an executable script")

# Then make the file executable and run it like this:
chmod +x script.py
./script.py

This approach is useful when you want a script to behave more like a small command-line tool.

Redirecting Python Script Output to a File

You can also send a script’s output to a text file instead of printing it to the terminal. This is useful for logs, reports, and simple exports.

python3 script.py > output.txt

Python script output redirection process

This pattern is common when you are working with scripts that generate text you want to save and review later. It also connects naturally with file-handling workflows such as reading and writing files in Python.

Also Read: Reading and Writing Files in Python

Common Errors When Running Python Scripts

Beginners often run into a few predictable issues the first time they try to execute a script. The table below gives the most common errors, what usually causes them, and how to fix them.

Error Cause Fix
Python not found Python is not installed or not in the PATH Install Python or try python3
Permission denied The script is not executable Run chmod +x script.py
SyntaxError Wrong syntax or incompatible Python version Check the code and verify the interpreter version
ModuleNotFoundError A required package is missing Install the dependency with pip install package_name

# Fix for Python not found

python3 script.py

# Fix for permission denied

chmod +x script.py

./script.py

# Fix for missing packages

pip install package_name

# Check your Python version

python3 –version

💡 Pro Tip: If you get python: command not found on macOS or Linux, try python3 instead. Python 2 is removed from many systems, so Python 3 is usually the correct command.

Take Your Python Skills to the Next Level

Learning how to run a Python script is just the beginning. To confidently apply Python in coding interviews and real-world scenarios, structured practice and expert guidance can make a big difference. The Fast-Track Your Interview Prep program is designed to help you bridge that gap.

  • Strong focus on data structures, algorithms, and core coding skills
  • Live mock interviews with engineers from top tech companies
  • 1:1 mentoring with personalized, actionable feedback
  • End-to-end career support, including resume and profile optimization

Want to turn your Python fundamentals into real interview confidence?

Conclusion

Now that you know how to run a Python script, you can choose the method that fits your task best: interactive mode for quick tests, the command line for direct execution, an IDE for everyday development, OS-specific commands for Windows, macOS, and Linux, and advanced methods for automation and troubleshooting.

Each approach helps you understand how Python code moves from a .py file to real output. For a deeper look at the interpreter and official behavior, see the Python docs. Practice a few examples on your own, and the process will start to feel natural very quickly.

FAQs: How to Run a Python Script

Q1. How do I install Python on my system?

Download the latest version from the official python.org website and run the installer. Make sure to check the box labeled Add Python to PATH before clicking install to ensure you can run Python from your terminal.

Q2. Where can I run Python code online?

Platforms like PythonAnywhere, Google Colab, and Repl.it allow you to write and execute code in a web browser. These are perfect for collaboration and running scripts without any local installation.

Q3. When should I provide the full file path to run a Python script?

You must provide the full path when your terminal is not currently in the same directory as the script. This ensures the Python interpreter can locate and load the file correctly from any system location.

Q4. How do I import one Python script into another?

To use code from one file in another, use the import keyword followed by the name of your file without the .py extension.

import my_script

my_script.my_function()

Q5. How do I make a Python file executable?

Include a shebang line like #!/usr/bin/env python3 at the very top of your file. Then, use the terminal command chmod +x your_script.py to grant execution permissions.

chmod +x script.py

./script.py

References

  1. Software Developers, Quality Assurance Analysts, and Testers
  2. How to run Python script on Ubuntu, Windows and MAC

Related Articles

Last updated on: March 28, 2026
Register for our webinar

Uplevel your career with AI/ML/GenAI

Loading_icon
Loading...
1 Enter details
2 Select webinar slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

Strange Tier-1 Neural “Power Patterns” Used By 20,013 FAANG Engineers To Ace Big Tech Interviews

100% Free — No credit card needed.

Register for our webinar

Uplevel your career with AI/ML/GenAI

Loading_icon
Loading...
1 Enter details
2 Select webinar slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

IK courses Recommended

Master ML interviews with DSA, ML System Design, Supervised/Unsupervised Learning, DL, and FAANG-level interview prep.

Fast filling course!

Get strategies to ace TPM interviews with training in program planning, execution, reporting, and behavioral frameworks.

Course covering SQL, ETL pipelines, data modeling, scalable systems, and FAANG interview prep to land top DE roles.

Course covering Embedded C, microcontrollers, system design, and debugging to crack FAANG-level Embedded SWE interviews.

Nail FAANG+ Engineering Management interviews with focused training for leadership, Scalable System Design, and coding.

End-to-end prep program to master FAANG-level SQL, statistics, ML, A/B testing, DL, and FAANG-level DS interviews.

Select a course based on your goals

Learn to build AI agents to automate your repetitive workflows

Upskill yourself with AI and Machine learning skills

Prepare for the toughest interviews with FAANG+ mentorship

Register for our webinar

How to Nail your next Technical Interview

Loading_icon
Loading...
1 Enter details
2 Select slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

Almost there...
Share your details for a personalised FAANG career consultation!
Your preferred slot for consultation * Required
Get your Resume reviewed * Max size: 4MB
Only the top 2% make it—get your resume FAANG-ready!

Registration completed!

🗓️ Friday, 18th April, 6 PM

Your Webinar slot

Mornings, 8-10 AM

Our Program Advisor will call you at this time

Register for our webinar

Transform Your Tech Career with AI Excellence

Transform Your Tech Career with AI Excellence

Join 25,000+ tech professionals who’ve accelerated their careers with cutting-edge AI skills

25,000+ Professionals Trained

₹23 LPA Average Hike 60% Average Hike

600+ MAANG+ Instructors

Webinar Slot Blocked

Interview Kickstart Logo

Register for our webinar

Transform your tech career

Transform your tech career

Learn about hiring processes, interview strategies. Find the best course for you.

Loading_icon
Loading...
*Invalid Phone Number

Used to send reminder for webinar

By sharing your contact details, you agree to our privacy policy.
Choose a slot

Time Zone: Asia/Kolkata

Choose a slot

Time Zone: Asia/Kolkata

Build AI/ML Skills & Interview Readiness to Become a Top 1% Tech Pro

Hands-on AI/ML learning + interview prep to help you win

Switch to ML: Become an ML-powered Tech Pro

Explore your personalized path to AI/ML/Gen AI success

Your preferred slot for consultation * Required
Get your Resume reviewed * Max size: 4MB
Only the top 2% make it—get your resume FAANG-ready!
Registration completed!
🗓️ Friday, 18th April, 6 PM
Your Webinar slot
Mornings, 8-10 AM
Our Program Advisor will call you at this time

Get tech interview-ready to navigate a tough job market

Best suitable for: Software Professionals with 5+ years of exprerience
Register for our FREE Webinar

Next webinar starts in

00
DAYS
:
00
HR
:
00
MINS
:
00
SEC

Your PDF Is One Step Away!

The 11 Neural “Power Patterns” For Solving Any FAANG Interview Problem 12.5X Faster Than 99.8% OF Applicants

The 2 “Magic Questions” That Reveal Whether You’re Good Enough To Receive A Lucrative Big Tech Offer

The “Instant Income Multiplier” That 2-3X’s Your Current Tech Salary