âčïž Skipped - page is already crawled
| Filter | Status | Condition | Details |
|---|---|---|---|
| HTTP status | PASS | download_http_code = 200 | HTTP 200 |
| Age cutoff | PASS | download_stamp > now() - 6 MONTH | 0.2 months ago |
| History drop | PASS | isNull(history_drop_reason) | No drop reason |
| Spam/ban | PASS | fh_dont_index != 1 AND ml_spam_score = 0 | ml_spam_score=0 |
| Canonical | PASS | meta_canonical IS NULL OR = '' OR = src_unparsed | Not set |
| Property | Value | |||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| URL | https://realpython.com/run-python-scripts/ | |||||||||
| Last Crawled | 2026-04-16 10:23:17 (6 days ago) | |||||||||
| First Indexed | 2019-02-18 06:40:36 (7 years ago) | |||||||||
| HTTP Status Code | 200 | |||||||||
| Content | ||||||||||
| Meta Title | How to Run Your Python Scripts and Code â Real Python | |||||||||
| Meta Description | Learn how to run Python scripts from the command line, REPL, IDEs, and file managers on Windows, Linux, and macOS. Master all execution approaches. | |||||||||
| Meta Canonical | null | |||||||||
| Boilerpipe Text | Running Python scripts is essential for executing your code. You can run Python scripts from the command line using
python script.py
, directly by making files executable with shebangs on Unix systems, or through IDEs and code editors. Python also supports interactive execution through the standard REPL for testing code snippets.
This tutorial covers the most common practical approaches for running Python scripts across Windows, Linux, and macOS.
By the end of this tutorial, youâll understand that:
The
python
command followed by a
script filename
executes the code from the
command line
on all operating systems.
Script mode runs code from
files sequentially
, while interactive mode uses the
REPL
for execution and testing with immediate feedback.
Unix systems require
executable permissions
and a
shebang line
like
#!/usr/bin/env python3
to run scripts directly as programs.
The
python
commandâs
-m
option runs
Python modules
by searching
sys.path
rather than requiring file paths.
IDEs like PyCharm and code editors like Visual Studio Code provide built-in options to
run scripts
from the environment interface.
To get the most out of this tutorial, you should know the basics of working with your operating systemâs
terminal
and file manager. Itâd also be beneficial to be familiar with a Python-friendly
IDE or code editor
and with the standard Python
REPL
(Read-Eval-Print Loop).
Take the Quiz:
Test your knowledge with our interactive âHow to Run Your Python Scriptsâ quiz. Youâll receive a score upon completion to help you track your learning progress:
Interactive Quiz
How to Run Your Python Scripts
One of the most important skills you need to build as a Python developer is to be able to run Python scripts and code. Test your understanding on how good you are with running your code.
What Scripts and Modules Are
In computing, the term
script
refers to a text file containing a logical sequence of orders that you can run to accomplish a specific task. These orders are typically expressed in a
scripting language
, which is a
programming language
that allows you to manipulate, customize, and automate tasks.
Scripting languages are usually
interpreted
at
runtime
rather than
compiled
. So, scripts are typically run by an
interpreter
, which is responsible for executing each order in a sequence.
Python
is an interpreted language. Because of that, Python programs are commonly called scripts. However, this terminology isnât completely accurate because Python programs can be way more complex than a simple, sequential script.
In general, a
file
containing executable Python
code
is called a scriptâor an
entry-point script
in more complex applicationsâwhich is a common term for a top-level
program
. On the other hand, a file containing Python code thatâs designed to be
imported
and used from another Python file is called a
module
.
So, the main difference between a
module
and a script is that modules store
importable code
while scripts hold
executable code
.
In the following sections, youâll learn how to run Python scripts, programs, and code in general. To kick things off, youâll start by learning how to run them from your operating systemâs command line or terminal.
How to Run Python Scripts From the Command Line
In Python programming, youâll write programs in plain text files. By convention, files containing Python code use the
.py
extension, and thereâs no distinction between scripts or executable programs and modules. All of them will use the same extension.
To create a Python script, you can use any Python-friendly
code editor or IDE
(integrated development environment). To keep moving forward in this tutorial, youâll need to create a basic script, so fire up your favorite text editor and create a new
hello.py
file containing the following code:
This is the classic
"Hello, World!"
program in Python. The executable code consists of a call to the built-in
print()
function that displays the
"Hello, World!"
message on your screen.
With this small program in place, youâre ready to learn different ways to run it. Youâll start by running the program from your command line, which is arguably the most commonly used approach to running scripts.
Using the
python
Command
To run Python scripts with the
python
command, you need to open a command-line window and type in the word
python
followed by the path to your target script:
Windows
Linux + macOS
After you press
Enter
, youâll see the phrase
Hello, World!
on your screen. If the previous command doesnât work right, then you may need to check if Python is in your systemâs
PATH
. You can also check where you saved
hello.py
.
Thatâs it! Youâve run your first script! Note that on Windows, you also have the option of using the
py
launcher, which triggers the
py.exe
launcher for console applications. This is the most basic and practical way to run Python scripts.
A useful feature of a terminal or
shell application
is that you can redirect the output of your commands using a straightforward syntax. This feature may be useful in those situations where you have a Python program that can generate a long output, and youâd like to save it to a file for later analysis.
In these scenarios, you can do something like the following:
In this command, the
>
symbol tells the shell to redirect the output of your command to the
output.txt
file, rather than to the standard system output, your screen. This process is commonly known as
redirection
, and it works on both Windows and
Unix-like
systems, such as Linux and macOS.
If the output file doesnât exist, then the shell automatically creates it. On the other hand, if the file already exists, then the shell overwrites its old content with the new output.
Finally, if you want to add the output of consecutive executions to the end of
output.txt
, then you can use two angle brackets (
>>
) instead of one:
Now, the shell app will append the current output to the end of
output.txt
. Youâll end up with a file containing the phrase
"Hello, World!"
twice.
Using the Scriptâs Filename Directly
On Windows, you can also run Python scripts by entering the name of the file containing the executable code at the command line:
Once youâve written the path to your script and pressed
Enter
, youâll note that a new terminal window appears on your screen for a few seconds, showing the script output. This is possible because Windows associates
.py
and
.pyw
files to
python.exe
and
pythonw.exe
, respectively.
This way of running Python scripts on Windows may be annoying because the code runs in a new terminal window that automatically closes after the execution ends. In most cases, you wonât be able to check the programâs output.
On Linux and macOS, you can also run your scripts directly. However, things are a bit different, and you need some additional setup steps. Go ahead and run the following command:
Linux
macOS
Unix systems prioritize security, which means that you canât go around executing any file as a program. So, you get a permission denied error when you try to run
hello.py
directly. To fix this issue, you need to explicitly tell the system that the file is executable. To do this, you can use the
chmod
command:
After running this command, your
hello.py
file will be executable. However, thatâs not enough for the script to run properly:
Why are you getting another error now? The problem is that your operating system (OS) doesnât know which program to use for running your script and is trying to run it with the shell itself. You can fix that by making a small addition to your
hello.py
file:
Youâve added a new line at the beginning of
hello.py
. It now starts with a Unix-style
shebang
, which is a special kind of
comment
that you can include in your scripts to tell the operating system which program to use for running the content of this file. In this case, you tell the OS to use Python.
Now you can run the script directly from your command line:
Wow! That was a long road! However, the effort was worth it. Now when you create a Python script to automate tasks in a Unix operating system, you know how to make it executable and run it from your command line.
Running Modules With the
-m
Option
The
python
command has a series of
command-line options
that can be useful in specific situations. For example, if you want to run a Python module, then you can use the command
python -m <module-name>
. The
-m
option searches Pythonâs
module search path
,
sys.path
, for the module name and runs its content:
In this example, you run the
hello.py
file as a module. This is possible because Python automatically adds the current directory to its
sys.path
list
. Note that the
module-name
argument needs to be the name of a module object, not a file name. In other words, you donât include the
.py
suffix.
If the target module isnât in
sys.path
, then you get an error:
In this example, the
missing
name isnât in the
sys.path
list, so Python isnât able to execute it, and therefore it returns an error.
How to Run Python Code Interactively
Running scripts isnât the only way to run Python code. Because Python is an interpreted language, you can use the interpreter to run code interactively. When you run the
python
command without arguments, you start a new interactive session, or
REPL
(Read-Eval-Print Loop). In there, you can run any Python code and get immediate feedback about how the code works.
In the following sections, youâll learn the basics of the Python interpreter and how to run code in it. This knowledge will be valuable for you, especially in those situations where you need to quickly test a small piece of Python code.
Getting to Know the Python Interpreter
Python is a high-level programming language with a clean and readable syntax. Python and its wide ecosystem of
packages
and libraries can boost your productivity in a
variety of fields
. The name Python also refers to a piece of software called the
interpreter
, which is the program that allows you to run Python code.
The interpreter is a layer of software that works between your program and your computer hardware to get your code running. Depending on the Python
implementation
that you use, the interpreter can be a program written in:
C
, like
CPython
, which is the core implementation of the language
Python itself, like
PyPy
, which is a
fast
implementation with a
just-in-time (JIT) compiler
Java
, like
Jython
, which can take advantage of the Java ecosystem
.NET, like
IronPython
, which uses the .NET ecosystem
Whatever interpreter you use, the code that you write will run in this program. Therefore, the first condition to be able to run scripts and code is to have the interpreter correctly
installed
on your operating system.
The Python interpreter can run code in two different modes:
Script
, or program
Interactive
, or REPL
In
script mode
, you use the interpreter to run a source file as an executable program, as you learned in the previous section. In this case, Python loads the file content and runs the code line by line, following the programâs execution flow.
Alternatively,
interactive mode
is when you launch the interpreter and use it as a platform to run code that you type in directly. This mode is pretty useful for learning Python as well as for developing, testing, and
debugging
your applications.
Running Python Code Interactively
Interactive sessions are a widely used tool for running Python code. To start a Python interactive session, or REPL, open a command-line window, type in the
python
command, and then press
Enter
.
These steps will take you into the Python interpreter, which looks something like the following:
Windows
Linux
macOS
The standard primary prompt for the interactive mode consists of three right angle brackets,
>>>
. So, as soon as you see these characters, youâll know that youâre in.
The Python interpreter is an interactive way to talk to your computer using the language. Itâs like live chat. Itâs also known as the REPL because it goes through four steps that run under the hood:
Reading
your input, which consists of Python code as
expressions
and
statements
Evaluating
your Python code, which generates a result or causes
side effects
Printing
any output so that you can check your codeâs results and get immediate feedback
Looping
back to step one to continue the interaction
This Python feature is a powerful tool that youâll wind up needing in your coding adventure, especially when youâre learning the language or when youâre in the early stages of a development process.
Once youâve started a REPL session, you can write and run Python code as you wish. The only drawback is that when you close the session, your code will be gone. This is another difference between the script and interactive modes:
scripts are persistent
.
When you work interactively, Python evaluates and executes every expression and statement immediately:
An interactive session allows you to test every piece of code immediately. Thatâs why this tool is an awesome development helper and an excellent space to experiment with the language and test ideas on the fly.
To leave interactive mode and jump back to the system shell, you can use one of the following options:
Executing the built-in
quit()
or
exit()
functions, which are plain commands (
quit
and
exit
) in
Python 3.13
or later
Pressing the
Ctrl
+
Z
and
Enter
key combination on Windows, or the
Ctrl
+
D
combination on Unix systems, such as Linux and macOS
Go ahead and give the Python REPL a try. Youâll see that itâs a great development tool that you must keep in your tool kit.
How to Run Scripts From Python Code
You can also run Python scripts and modules from an interactive session or from a
.py
file. This option opens a variety of possibilities. In the following sections, youâll explore a few tools and techniques that will allow you to run scripts and code from Python code.
Taking Advantage of
import
Statements
When you
import a module
from another module, script, or interactive session, what really happens is that Python loads its contents for later access and use. The interesting point is that the
import
statement runs any executable code in the imported module.
When the module contains only
class
, function,
variable
, and
constant
definitions, you probably wonât be aware that the code was run. However, when the module includes calls to functions,
methods
, or other
statements
that generate visible results, then youâll witness its execution.
This provides you with another approach to run scripts:
Youâll note that
import
runs the code only once per session. After you first import a module, successive imports do nothing, even if you modify the content of the module. This is because
import
operations are expensive, and Python takes some extra steps to optimize overall performance:
These two imports do nothing because Python knows that the
hello
module was already imported. Therefore, Python skips the import. This behavior may seem annoying, especially when youâre working on a module and trying to test your changes in an interactive session. However, itâs an intentional optimization.
Using the
importlib
Standard-Library Module
In the Python
standard library
, you can find the
importlib
module. This module provides the
import_module()
function, which allows you to programmatically import modules.
With
import_module()
, you can emulate an
import
operation and, therefore, execute any module or script. Take a look at this example:
The
import_module()
function imports a module programmatically using its name. This action runs any executable code in the target module. Thatâs why you get
Hello, World!
on your screen.
You already know that once youâve imported a module for the first time, you wonât be able to import it again using another
import
statement. If you want to reload the module and run it once again, then you can use the
reload()
function, which forces the interpreter to import the module again:
An important point to note here is that the argument of
reload()
has to be the name of a module object, not a
string
. So, to use
reload()
successfully, you need to provide a module thatâs already imported.
Leveraging the Power of the Built-in
exec()
Function
So far, youâve learned about some handy ways to run Python scripts. In this section, youâll learn how to do that by using the built-in
exec()
function, which supports the dynamic execution of Python code.
The
exec()
function provides an alternative way to run your scripts from inside your code:
In this example, you use the
with
statement
to open the
hello.py
file for reading. Then, you read the fileâs content with the
.read()
method. This method returns a
string
that you pass to
exec()
for execution.
You must be careful when using the
exec()
function because it implies some important security risks, especially if youâre using it for executing external code from untrusted sources. To learn more about this function, check out
Pythonâs
exec()
: Execute Dynamically Generated Code
.
How to Run Python Scripts on IDEs and Code Editors
For developing a large and complex application, you should use an
integrated development environment (IDE)
or an advanced text editor that incorporates programmer-friendly features.
Most of these programs have options that allow you to run your scripts from inside the environment itself. Itâs common for them to include a
Run
or
Build
action, which is usually available from the toolbar or from the main menu.
Pythonâs standard distribution comes with
IDLE
as its default IDE. You can use this program to write, debug, modify, and run your modules and scripts. Other IDEs, such as
PyCharm
and
Thonny
, also allow you to run scripts from inside the environment. For example, in PyCharm, you can press
Ctrl
+
R
on your keyboard to quickly run your appâs entry-point script.
Advanced code editors like
Visual Studio Code
also allow you to run your scripts. In Visual Studio Code, you can press
Ctrl
+
F5
to run the file thatâs currently active, for example.
To learn how to run Python scripts from your preferred IDE or code editor, check its specific documentation or take a quick look at the programâs GUI. Youâll quickly figure out the answer.
How to Run Python Scripts From a File Manager
Running a script by double-clicking its icon in a
file manager
is another way to run your Python scripts. You probably wonât use this option much in the development stage, but you may use it when you release your code for production.
In order to run your scripts with a double click, you must satisfy some conditions that will depend on your operating system.
Windows, for example, associates the extensions
.py
and
.pyw
with the programs
python.exe
and
pythonw.exe
, respectively. This allows you to run your scripts by double-clicking on their icons.
On Unix systems, youâll probably be able to run your scripts by double-clicking on them in your file manager. To achieve this, your script must have execution permissions, and youâll need to use the shebang trick that youâve already learned. Like on Windows, you may not see any output on-screen when it comes to command-line interface scripts.
The execution of scripts through a double click has several limitations and depends on many factors, such as the operating system, the file manager, execution permissions, and file associations. Still, you can consider this alternative a viable option for some utility scripts.
Conclusion
Youâve acquired the knowledge and skills that you need for running Python scripts and code in several ways and in a variety of situations and development environments. The command line will be your best friend when you need to run production-ready scripts. During development, your IDE or code editor will provide the right option to run your code.
In this tutorial, youâve learned how to:
Run Python scripts from the
command line
or
terminal
in your current OS
Execute code in
interactive mode
using Pythonâs standard REPL
Use your favorite
IDE
or
code editor
to run Python scripts during development
Launch scripts and programs from your operating systemâs
file manager
These skills are essential for you as a Python developer. Theyâll make your development process much faster, as well as more productive and flexible.
Take the Quiz:
Test your knowledge with our interactive âHow to Run Your Python Scriptsâ quiz. Youâll receive a score upon completion to help you track your learning progress:
Interactive Quiz
How to Run Your Python Scripts
One of the most important skills you need to build as a Python developer is to be able to run Python scripts and code. Test your understanding on how good you are with running your code.
Frequently Asked Questions
Now that you have some experience with running Python scripts and code, you can use the questions and answers below to check your understanding and recap what youâve learned.
These FAQs are related to the most important concepts youâve covered in this tutorial. Click the
Show/Hide
toggle beside each question to reveal the answer.
To run a Python script from the command line, open a terminal or command prompt and type
python
followed by the path to your script file. For example,
python hello.py
. On Windows, you might also use
py
instead of
python
. If you see any errors, check that Python is added to your systemâs PATH variable.
In script mode, you execute a file containing Python code using the Python interpreter, and the code runs sequentially. In interactive mode, you use the Python interpreter to run code directly, one statement at a time, often in a REPL (Read-Eval-Print Loop). This allows for immediate feedback and experimentation.
Yes. On Windows, you can double-click
.py
files to run them since theyâre associated with
python.exe
. On Unix systems, you need to ensure that the script has execution permissions and includes a shebang (
#!/usr/bin/env python3
) as the first line. However, this method may not display output for console applications.
You can execute a Python module using the command line with the
-m
option. For example,
python -m module_name
. This runs the module as a script, provided itâs available in the Python module search path.
Besides the command line, you can run Python scripts using an IDE (Integrated Development Environment) like PyCharm or Thonny, a code editor like Visual Studio Code, or from an interactive session using the Python REPL. Each environment provides additional features to aid development and debugging. | |||||||||
| Markdown | [](https://realpython.com/)
- [Start Here](https://realpython.com/start-here/)
- [Learn Python](https://realpython.com/run-python-scripts/)
[Python Tutorials â In-depth articles and video courses](https://realpython.com/search?kind=article&kind=course&order=newest)
[Learning Paths â Guided study plans for accelerated learning](https://realpython.com/learning-paths/)
[Quizzes & Exercises â Check your learning progress](https://realpython.com/quizzes/)
[Browse Topics â Focus on a specific area or skill level](https://realpython.com/tutorials/all/)
[Community Chat â Learn with other Pythonistas](https://realpython.com/community/)
[Office Hours â Live Q\&A calls with Python experts](https://realpython.com/office-hours/)
[Live Courses â Live, instructor-led Python courses](https://realpython.com/live/)
[Podcast â Hear whatâs new in the world of Python](https://realpython.com/podcasts/rpp/)
[Books â Round out your knowledge and learn offline](https://realpython.com/products/books/)
[Reference â Concise definitions for common Python terms](https://realpython.com/ref/)
[Code Mentor âBeta Personalized code assistance & learning tools](https://realpython.com/mentor/)
[Unlock All Content â](https://realpython.com/account/join/)
- [More](https://realpython.com/run-python-scripts/)
[Learner Stories](https://realpython.com/learner-stories/) [Python Newsletter](https://realpython.com/newsletter/) [Python Job Board](https://www.pythonjobshq.com/) [Meet the Team](https://realpython.com/team/) [Become a Contributor](https://realpython.com/jobs/)
- [Search](https://realpython.com/search "Search")
- [Join](https://realpython.com/account/join/)
- [SignâIn](https://realpython.com/account/login/?next=%2Frun-python-scripts%2F)
[Browse Topics](https://realpython.com/tutorials/all/)
[Guided Learning Paths](https://realpython.com/learning-paths/)
[Basics](https://realpython.com/search?level=basics)
[Intermediate](https://realpython.com/search?level=intermediate)
[Advanced](https://realpython.com/search?level=advanced)
***
[ai](https://realpython.com/tutorials/ai/) [algorithms](https://realpython.com/tutorials/algorithms/) [api](https://realpython.com/tutorials/api/) [best-practices](https://realpython.com/tutorials/best-practices/) [career](https://realpython.com/tutorials/career/) [community](https://realpython.com/tutorials/community/) [databases](https://realpython.com/tutorials/databases/) [data-science](https://realpython.com/tutorials/data-science/) [data-structures](https://realpython.com/tutorials/data-structures/) [data-viz](https://realpython.com/tutorials/data-viz/) [devops](https://realpython.com/tutorials/devops/) [django](https://realpython.com/tutorials/django/) [docker](https://realpython.com/tutorials/docker/) [editors](https://realpython.com/tutorials/editors/) [flask](https://realpython.com/tutorials/flask/) [front-end](https://realpython.com/tutorials/front-end/) [gamedev](https://realpython.com/tutorials/gamedev/) [gui](https://realpython.com/tutorials/gui/) [machine-learning](https://realpython.com/tutorials/machine-learning/) [news](https://realpython.com/tutorials/news/) [numpy](https://realpython.com/tutorials/numpy/) [projects](https://realpython.com/tutorials/projects/) [python](https://realpython.com/tutorials/python/) [stdlib](https://realpython.com/tutorials/stdlib/) [testing](https://realpython.com/tutorials/testing/) [tools](https://realpython.com/tutorials/tools/) [web-dev](https://realpython.com/tutorials/web-dev/) [web-scraping](https://realpython.com/tutorials/web-scraping/)
[Table of Contents](https://realpython.com/run-python-scripts/#toc)
- [What Scripts and Modules Are](https://realpython.com/run-python-scripts/#what-scripts-and-modules-are)
- [How to Run Python Scripts From the Command Line](https://realpython.com/run-python-scripts/#how-to-run-python-scripts-from-the-command-line)
- [Using the python Command](https://realpython.com/run-python-scripts/#using-the-python-command)
- [Using the Scriptâs Filename Directly](https://realpython.com/run-python-scripts/#using-the-scripts-filename-directly)
- [Running Modules With the -m Option](https://realpython.com/run-python-scripts/#running-modules-with-the-m-option)
- [How to Run Python Code Interactively](https://realpython.com/run-python-scripts/#how-to-run-python-code-interactively)
- [Getting to Know the Python Interpreter](https://realpython.com/run-python-scripts/#getting-to-know-the-python-interpreter)
- [Running Python Code Interactively](https://realpython.com/run-python-scripts/#running-python-code-interactively)
- [How to Run Scripts From Python Code](https://realpython.com/run-python-scripts/#how-to-run-scripts-from-python-code)
- [Taking Advantage of import Statements](https://realpython.com/run-python-scripts/#taking-advantage-of-import-statements)
- [Using the importlib Standard-Library Module](https://realpython.com/run-python-scripts/#using-the-importlib-standard-library-module)
- [Leveraging the Power of the Built-in exec() Function](https://realpython.com/run-python-scripts/#leveraging-the-power-of-the-built-in-exec-function)
- [How to Run Python Scripts on IDEs and Code Editors](https://realpython.com/run-python-scripts/#how-to-run-python-scripts-on-ides-and-code-editors)
- [How to Run Python Scripts From a File Manager](https://realpython.com/run-python-scripts/#how-to-run-python-scripts-from-a-file-manager)
- [Conclusion](https://realpython.com/run-python-scripts/#conclusion)
- [Frequently Asked Questions](https://realpython.com/run-python-scripts/#frequently-asked-questions)
Mark as Completed
Share
Recommended Course
[ How to Run a Python Script 24m · 8 lessons](https://realpython.com/courses/running-python-scripts/)

# How to Run Your Python Scripts and Code
by [Leodanis Pozo Ramos](https://realpython.com/run-python-scripts/#author)
Publication date
Feb 25, 2026
Reading time estimate
24m
[34 Comments](https://realpython.com/run-python-scripts/#reader-comments)
[basics](https://realpython.com/tutorials/basics/) [best-practices](https://realpython.com/tutorials/best-practices/) [devops](https://realpython.com/tutorials/devops/) [python](https://realpython.com/tutorials/python/)
Mark as Completed
Share
Table of Contents
- [What Scripts and Modules Are](https://realpython.com/run-python-scripts/#what-scripts-and-modules-are)
- [How to Run Python Scripts From the Command Line](https://realpython.com/run-python-scripts/#how-to-run-python-scripts-from-the-command-line)
- [Using the python Command](https://realpython.com/run-python-scripts/#using-the-python-command)
- [Using the Scriptâs Filename Directly](https://realpython.com/run-python-scripts/#using-the-scripts-filename-directly)
- [Running Modules With the -m Option](https://realpython.com/run-python-scripts/#running-modules-with-the-m-option)
- [How to Run Python Code Interactively](https://realpython.com/run-python-scripts/#how-to-run-python-code-interactively)
- [Getting to Know the Python Interpreter](https://realpython.com/run-python-scripts/#getting-to-know-the-python-interpreter)
- [Running Python Code Interactively](https://realpython.com/run-python-scripts/#running-python-code-interactively)
- [How to Run Scripts From Python Code](https://realpython.com/run-python-scripts/#how-to-run-scripts-from-python-code)
- [Taking Advantage of import Statements](https://realpython.com/run-python-scripts/#taking-advantage-of-import-statements)
- [Using the importlib Standard-Library Module](https://realpython.com/run-python-scripts/#using-the-importlib-standard-library-module)
- [Leveraging the Power of the Built-in exec() Function](https://realpython.com/run-python-scripts/#leveraging-the-power-of-the-built-in-exec-function)
- [How to Run Python Scripts on IDEs and Code Editors](https://realpython.com/run-python-scripts/#how-to-run-python-scripts-on-ides-and-code-editors)
- [How to Run Python Scripts From a File Manager](https://realpython.com/run-python-scripts/#how-to-run-python-scripts-from-a-file-manager)
- [Conclusion](https://realpython.com/run-python-scripts/#conclusion)
- [Frequently Asked Questions](https://realpython.com/run-python-scripts/#frequently-asked-questions)
[Remove ads](https://realpython.com/account/join/)
Recommended Course
[How to Run a Python Script](https://realpython.com/courses/running-python-scripts/) (24m)
Running Python scripts is essential for executing your code. You can run Python scripts from the command line using `python script.py`, directly by making files executable with shebangs on Unix systems, or through IDEs and code editors. Python also supports interactive execution through the standard REPL for testing code snippets.
This tutorial covers the most common practical approaches for running Python scripts across Windows, Linux, and macOS.
**By the end of this tutorial, youâll understand that:**
- The **`python`** command followed by a **script filename** executes the code from the **command line** on all operating systems.
- Script mode runs code from **files sequentially**, while interactive mode uses the **REPL** for execution and testing with immediate feedback.
- Unix systems require **executable permissions** and a **shebang line** like `#!/usr/bin/env python3` to run scripts directly as programs.
- The `python` commandâs `-m` option runs **Python modules** by searching `sys.path` rather than requiring file paths.
- IDEs like PyCharm and code editors like Visual Studio Code provide built-in options to **run scripts** from the environment interface.
To get the most out of this tutorial, you should know the basics of working with your operating systemâs [terminal](https://realpython.com/terminal-commands/) and file manager. Itâd also be beneficial to be familiar with a Python-friendly [IDE or code editor](https://realpython.com/python-ides-code-editors-guide/) and with the standard Python [REPL](https://realpython.com/python-repl/) (Read-Eval-Print Loop).
**Free Download:** [Get a sample chapter from Python Tricks: The Book](https://realpython.com/bonus/python-tricks-sample-pdf/) that shows you Pythonâs best practices with simple examples you can apply instantly to write more beautiful + Pythonic code.
***Take the Quiz:*** Test your knowledge with our interactive âHow to Run Your Python Scriptsâ quiz. Youâll receive a score upon completion to help you track your learning progress:
***
[](https://realpython.com/quizzes/run-python-scripts/)
**Interactive Quiz**
[How to Run Your Python Scripts](https://realpython.com/quizzes/run-python-scripts/)
One of the most important skills you need to build as a Python developer is to be able to run Python scripts and code. Test your understanding on how good you are with running your code.
## What Scripts and Modules Are
In computing, the term **script** refers to a text file containing a logical sequence of orders that you can run to accomplish a specific task. These orders are typically expressed in a [scripting language](https://en.wikipedia.org/wiki/Scripting_language), which is a [programming language](https://en.wikipedia.org/wiki/Programming_language) that allows you to manipulate, customize, and automate tasks.
Scripting languages are usually [interpreted](https://en.wikipedia.org/wiki/Interpreter_\(computing\)) at [runtime](https://en.wikipedia.org/wiki/Runtime_\(program_lifecycle_phase\)) rather than [compiled](https://en.wikipedia.org/wiki/Compiler). So, scripts are typically run by an [interpreter](https://realpython.com/ref/glossary/interpreter/), which is responsible for executing each order in a sequence.
[Python](https://realpython.com/ref/glossary/python/) is an interpreted language. Because of that, Python programs are commonly called scripts. However, this terminology isnât completely accurate because Python programs can be way more complex than a simple, sequential script.
In general, a [file](https://realpython.com/ref/glossary/text-file/) containing executable Python [code](https://realpython.com/ref/glossary/source-code/) is called a scriptâor an **entry-point script** in more complex applicationsâwhich is a common term for a top-level **program**. On the other hand, a file containing Python code thatâs designed to be [imported](https://realpython.com/python-import/) and used from another Python file is called a [**module**](https://realpython.com/ref/glossary/module/).
So, the main difference between a [module](https://realpython.com/python-modules-packages/) and a script is that modules store **importable code** while scripts hold **executable code**.
**Note:** Importable code is code that defines something but doesnât perform a specific action. Some examples include [function](https://realpython.com/ref/glossary/function/) and [class](https://realpython.com/ref/glossary/class/) definitions. In contrast, executable code is code that performs specific actions. Some examples include [function calls](https://realpython.com/defining-your-own-python-function/#calling-functions-in-python), [loops](https://realpython.com/ref/glossary/loop/), and [conditionals](https://realpython.com/python-conditional-statements/).
In the following sections, youâll learn how to run Python scripts, programs, and code in general. To kick things off, youâll start by learning how to run them from your operating systemâs command line or terminal.
[Remove ads](https://realpython.com/account/join/)
## How to Run Python Scripts From the Command Line
In Python programming, youâll write programs in plain text files. By convention, files containing Python code use the `.py` extension, and thereâs no distinction between scripts or executable programs and modules. All of them will use the same extension.
**Note:** On [Windows](https://realpython.com/python-coding-setup-windows/) systems, the extension can also be `.pyw` for those applications that should use the `pythonw.exe` launcher.
To create a Python script, you can use any Python-friendly [code editor or IDE](https://realpython.com/python-ides-code-editors-guide/) (integrated development environment). To keep moving forward in this tutorial, youâll need to create a basic script, so fire up your favorite text editor and create a new `hello.py` file containing the following code:
Python `hello.py`
```
print("Hello, World!")
```
This is the classic `"Hello, World!"` program in Python. The executable code consists of a call to the built-in [`print()`](https://realpython.com/python-print/) function that displays the `"Hello, World!"` message on your screen.
With this small program in place, youâre ready to learn different ways to run it. Youâll start by running the program from your command line, which is arguably the most commonly used approach to running scripts.
### Using the `python` Command
To run Python scripts with the `python` command, you need to open a command-line window and type in the word `python` followed by the path to your target script:
- [Windows](https://realpython.com/run-python-scripts/#windows-1)
- [Linux + macOS](https://realpython.com/run-python-scripts/#linux-macos-1)
Windows PowerShell
```
```
Shell
```
```
After you press `Enter`, youâll see the phrase `Hello, World!` on your screen. If the previous command doesnât work right, then you may need to check if Python is in your systemâs [`PATH`](https://realpython.com/add-python-to-path/). You can also check where you saved `hello.py`.
**Note:** In some Linux distributions and probably in some macOS versions, you may need to use the `python3` command instead of `python`.
Thatâs it! Youâve run your first script! Note that on Windows, you also have the option of using the `py` launcher, which triggers the `py.exe` launcher for console applications. This is the most basic and practical way to run Python scripts.
**Note:** If youâve never worked with the command line or terminal, then you can try the following, depending on your operating system:
- On Windows, recent versions of the OS come with an application called PowerShell that you can quickly run from the *Search* box. Once youâve launched this program, you can start running commands in it.
- On macOS, you can access the system terminal from the Launchpad by typing *Terminal* and pressing `Enter` when the app appears.
- On Linux, there are several applications that give you access to the system command line. In many desktop environments, you can quickly access the default terminal by pressing `Ctrl`\+`Alt`\+`T`.
To learn more about using the command line or terminal, check out [The Terminal: First Steps and Useful Commands](https://realpython.com/terminal-commands/).
A useful feature of a terminal or [shell application](https://en.wikipedia.org/wiki/Unix_shell) is that you can redirect the output of your commands using a straightforward syntax. This feature may be useful in those situations where you have a Python program that can generate a long output, and youâd like to save it to a file for later analysis.
In these scenarios, you can do something like the following:
Shell
```
$ python hello.py > output.txt
```
In this command, the `>` symbol tells the shell to redirect the output of your command to the `output.txt` file, rather than to the standard system output, your screen. This process is commonly known as [redirection](https://en.wikipedia.org/wiki/Redirection_\(computing\)), and it works on both Windows and [Unix-like](https://en.wikipedia.org/wiki/Unix) systems, such as Linux and macOS.
If the output file doesnât exist, then the shell automatically creates it. On the other hand, if the file already exists, then the shell overwrites its old content with the new output.
Finally, if you want to add the output of consecutive executions to the end of `output.txt`, then you can use two angle brackets (`>>`) instead of one:
Shell
```
$ python hello.py >> output.txt
```
Now, the shell app will append the current output to the end of `output.txt`. Youâll end up with a file containing the phrase `"Hello, World!"` twice.
[Remove ads](https://realpython.com/account/join/)
### Using the Scriptâs Filename Directly
On Windows, you can also run Python scripts by entering the name of the file containing the executable code at the command line:
Windows Command Prompt
```
PS> .\hello.py
```
Once youâve written the path to your script and pressed `Enter`, youâll note that a new terminal window appears on your screen for a few seconds, showing the script output. This is possible because Windows associates `.py` and `.pyw` files to `python.exe` and `pythonw.exe`, respectively.
This way of running Python scripts on Windows may be annoying because the code runs in a new terminal window that automatically closes after the execution ends. In most cases, you wonât be able to check the programâs output.
On Linux and macOS, you can also run your scripts directly. However, things are a bit different, and you need some additional setup steps. Go ahead and run the following command:
- [Linux](https://realpython.com/run-python-scripts/#linux-2)
- [macOS](https://realpython.com/run-python-scripts/#macos-2)
Shell
```
```
Shell
```
```
Unix systems prioritize security, which means that you canât go around executing any file as a program. So, you get a permission denied error when you try to run `hello.py` directly. To fix this issue, you need to explicitly tell the system that the file is executable. To do this, you can use the `chmod` command:
Shell
```
$ chmod +x hello.py
```
After running this command, your `hello.py` file will be executable. However, thatâs not enough for the script to run properly:
Shell
```
```
Why are you getting another error now? The problem is that your operating system (OS) doesnât know which program to use for running your script and is trying to run it with the shell itself. You can fix that by making a small addition to your `hello.py` file:
Python `hello.py`
```
```
Youâve added a new line at the beginning of `hello.py`. It now starts with a Unix-style [shebang](https://realpython.com/python-shebang/), which is a special kind of [comment](https://realpython.com/python-comments-guide/) that you can include in your scripts to tell the operating system which program to use for running the content of this file. In this case, you tell the OS to use Python.
**Note:** Youâll have at least two different ways to specify the path to the interpreter in the shebang comment:
1. Provide the absolute path to the interpreter, like in **`#!/usr/bin/python3`**
2. Use the operating systemâs `env` command, like in **`#!/usr/bin/env python3`**
The first approach is less portable because not all Unix systems place the Python interpreter in the same directory. In contrast, the second approach is safer and more portable. It invokes the `env` command to find out where the interpreter lives.
Now you can run the script directly from your command line:
Shell
```
```
Wow! That was a long road! However, the effort was worth it. Now when you create a Python script to automate tasks in a Unix operating system, you know how to make it executable and run it from your command line.
### Running Modules With the `-m` Option
The `python` command has a series of [command-line options](https://realpython.com/python-command-line-arguments/) that can be useful in specific situations. For example, if you want to run a Python module, then you can use the command `python -m <module-name>`. The `-m` option searches Pythonâs [module search path](https://docs.python.org/3/tutorial/modules.html#the-module-search-path), `sys.path`, for the module name and runs its content:
Shell
```
```
In this example, you run the `hello.py` file as a module. This is possible because Python automatically adds the current directory to its `sys.path` [list](https://realpython.com/ref/builtin-types/list/). Note that the `module-name` argument needs to be the name of a module object, not a file name. In other words, you donât include the `.py` suffix.
**Note:** Using the `-m` option is common practice when you need to use the [command-line interface (CLI)](https://realpython.com/command-line-interfaces-python-argparse/#command-line-interfaces-clis) of [standard-library](https://realpython.com/ref/glossary/standard-library/) modules, such as [`pip`](https://realpython.com/what-is-pip/), [`venv`](https://realpython.com/python-virtual-environments-a-primer/), [`http.server`](https://realpython.com/python-http-server/), and [`zipfile`](https://realpython.com/python-zipfile/#running-zipfile-from-your-command-line).
If the target module isnât in `sys.path`, then you get an error:
Shell
```
```
In this example, the `missing` name isnât in the `sys.path` list, so Python isnât able to execute it, and therefore it returns an error.
[Remove ads](https://realpython.com/account/join/)
## How to Run Python Code Interactively
Running scripts isnât the only way to run Python code. Because Python is an interpreted language, you can use the interpreter to run code interactively. When you run the `python` command without arguments, you start a new interactive session, or [REPL](https://realpython.com/python-repl/) (Read-Eval-Print Loop). In there, you can run any Python code and get immediate feedback about how the code works.
In the following sections, youâll learn the basics of the Python interpreter and how to run code in it. This knowledge will be valuable for you, especially in those situations where you need to quickly test a small piece of Python code.
### Getting to Know the Python Interpreter
Python is a high-level programming language with a clean and readable syntax. Python and its wide ecosystem of [packages](https://realpython.com/ref/glossary/package/) and libraries can boost your productivity in a [variety of fields](https://realpython.com/what-can-i-do-with-python/). The name Python also refers to a piece of software called the **interpreter**, which is the program that allows you to run Python code.
The interpreter is a layer of software that works between your program and your computer hardware to get your code running. Depending on the Python [implementation](https://www.python.org/download/alternatives/) that you use, the interpreter can be a program written in:
- [C](https://realpython.com/c-for-python-programmers/), like [CPython](https://realpython.com/cpython-source-code-guide/), which is the core implementation of the language
- Python itself, like [PyPy](https://realpython.com/pypy-faster-python/), which is a [fast](http://speed.pypy.org/) implementation with a [just-in-time (JIT) compiler](https://en.wikipedia.org/wiki/Just-in-time_compilation)
- [Java](https://realpython.com/oop-in-python-vs-java/), like [Jython](http://www.jython.org/index.html), which can take advantage of the Java ecosystem
- .NET, like [IronPython](http://ironpython.net/), which uses the .NET ecosystem
Whatever interpreter you use, the code that you write will run in this program. Therefore, the first condition to be able to run scripts and code is to have the interpreter correctly [installed](https://realpython.com/installing-python/) on your operating system.
The Python interpreter can run code in two different modes:
1. [Script](https://realpython.com/run-python-scripts/), or program
2. [Interactive](https://realpython.com/interacting-with-python/), or REPL
In **script mode**, you use the interpreter to run a source file as an executable program, as you learned in the previous section. In this case, Python loads the file content and runs the code line by line, following the programâs execution flow.
Alternatively, **interactive mode** is when you launch the interpreter and use it as a platform to run code that you type in directly. This mode is pretty useful for learning Python as well as for developing, testing, and [debugging](https://realpython.com/ref/glossary/debugging/) your applications.
### Running Python Code Interactively
Interactive sessions are a widely used tool for running Python code. To start a Python interactive session, or REPL, open a command-line window, type in the `python` command, and then press `Enter`.
These steps will take you into the Python interpreter, which looks something like the following:
- [Windows](https://realpython.com/run-python-scripts/#windows-3)
- [Linux](https://realpython.com/run-python-scripts/#linux-3)
- [macOS](https://realpython.com/run-python-scripts/#macos-3)
Windows PowerShell
```
```
Shell
```
```
Shell
```
```
The standard primary prompt for the interactive mode consists of three right angle brackets, `>>>`. So, as soon as you see these characters, youâll know that youâre in.
**Note:** The standard REPL also has a secondary prompt that consists of three periods (`...`). This prompt appears when you add indented lines to a [compound statement](https://docs.python.org/3/reference/compound_stmts.html), such as conditionals, function and class definitions, and loops.
The Python interpreter is an interactive way to talk to your computer using the language. Itâs like live chat. Itâs also known as the REPL because it goes through four steps that run under the hood:
1. **Reading** your input, which consists of Python code as [expressions](https://docs.python.org/3/glossary.html#term-expression) and [statements](https://docs.python.org/3/glossary.html#term-statement)
2. **Evaluating** your Python code, which generates a result or causes [side effects](https://en.wikipedia.org/wiki/Side_effect_\(computer_science\))
3. **Printing** any output so that you can check your codeâs results and get immediate feedback
4. **Looping** back to step one to continue the interaction
This Python feature is a powerful tool that youâll wind up needing in your coding adventure, especially when youâre learning the language or when youâre in the early stages of a development process.
Once youâve started a REPL session, you can write and run Python code as you wish. The only drawback is that when you close the session, your code will be gone. This is another difference between the script and interactive modes: *scripts are persistent*.
When you work interactively, Python evaluates and executes every expression and statement immediately:
Python
```
```
An interactive session allows you to test every piece of code immediately. Thatâs why this tool is an awesome development helper and an excellent space to experiment with the language and test ideas on the fly.
To leave interactive mode and jump back to the system shell, you can use one of the following options:
- Executing the built-in `quit()` or `exit()` functions, which are plain commands (`quit` and `exit`) in [Python 3.13](https://realpython.com/python313-new-features/) or later
- Pressing the `Ctrl`\+`Z` and `Enter` key combination on Windows, or the `Ctrl`\+`D` combination on Unix systems, such as Linux and macOS
Go ahead and give the Python REPL a try. Youâll see that itâs a great development tool that you must keep in your tool kit.
[Remove ads](https://realpython.com/account/join/)
## How to Run Scripts From Python Code
You can also run Python scripts and modules from an interactive session or from a `.py` file. This option opens a variety of possibilities. In the following sections, youâll explore a few tools and techniques that will allow you to run scripts and code from Python code.
### Taking Advantage of `import` Statements
When you [import a module](https://realpython.com/absolute-vs-relative-python-imports/) from another module, script, or interactive session, what really happens is that Python loads its contents for later access and use. The interesting point is that the [`import`](https://realpython.com/ref/keywords/import/) statement runs any executable code in the imported module.
When the module contains only [class](https://realpython.com/python-classes/), function, [variable](https://realpython.com/python-variables/), and [constant](https://realpython.com/python-constants/) definitions, you probably wonât be aware that the code was run. However, when the module includes calls to functions, [methods](https://realpython.com/ref/glossary/method/), or other [statements](https://realpython.com/ref/glossary/statement/) that generate visible results, then youâll witness its execution.
This provides you with another approach to run scripts:
Python
```
```
Youâll note that `import` runs the code only once per session. After you first import a module, successive imports do nothing, even if you modify the content of the module. This is because `import` operations are expensive, and Python takes some extra steps to optimize overall performance:
Python
```
```
These two imports do nothing because Python knows that the `hello` module was already imported. Therefore, Python skips the import. This behavior may seem annoying, especially when youâre working on a module and trying to test your changes in an interactive session. However, itâs an intentional optimization.
### Using the `importlib` Standard-Library Module
In the Python [standard library](https://docs.python.org/3/library/index.html), you can find the [`importlib`](https://realpython.com/ref/stdlib/importlib/) module. This module provides the [`import_module()`](https://docs.python.org/3/library/importlib.html#importlib.import_module) function, which allows you to programmatically import modules.
With `import_module()`, you can emulate an `import` operation and, therefore, execute any module or script. Take a look at this example:
Python
```
```
The `import_module()` function imports a module programmatically using its name. This action runs any executable code in the target module. Thatâs why you get `Hello, World!` on your screen.
You already know that once youâve imported a module for the first time, you wonât be able to import it again using another `import` statement. If you want to reload the module and run it once again, then you can use the [`reload()`](https://docs.python.org/3/library/importlib.html#importlib.reload) function, which forces the interpreter to import the module again:
Python
```
```
An important point to note here is that the argument of `reload()` has to be the name of a module object, not a [string](https://realpython.com/python-strings/). So, to use `reload()` successfully, you need to provide a module thatâs already imported.
### Leveraging the Power of the Built-in `exec()` Function
So far, youâve learned about some handy ways to run Python scripts. In this section, youâll learn how to do that by using the built-in [`exec()`](https://realpython.com/python-exec/) function, which supports the dynamic execution of Python code.
The [`exec()`](https://realpython.com/ref/builtin-functions/exec/) function provides an alternative way to run your scripts from inside your code:
Python
```
```
In this example, you use the [`with` statement](https://realpython.com/python-with-statement/) to open the `hello.py` file for reading. Then, you read the fileâs content with the `.read()` method. This method returns a [string](https://realpython.com/ref/builtin-types/str/) that you pass to `exec()` for execution.
You must be careful when using the `exec()` function because it implies some important security risks, especially if youâre using it for executing external code from untrusted sources. To learn more about this function, check out [Pythonâs `exec()`: Execute Dynamically Generated Code](https://realpython.com/python-exec/).
[Remove ads](https://realpython.com/account/join/)
## How to Run Python Scripts on IDEs and Code Editors
For developing a large and complex application, you should use an [integrated development environment (IDE)](https://realpython.com/ref/glossary/ide/) or an advanced text editor that incorporates programmer-friendly features.
Most of these programs have options that allow you to run your scripts from inside the environment itself. Itâs common for them to include a *Run* or *Build* action, which is usually available from the toolbar or from the main menu.
Pythonâs standard distribution comes with [IDLE](https://realpython.com/python-idle/) as its default IDE. You can use this program to write, debug, modify, and run your modules and scripts. Other IDEs, such as [PyCharm](https://realpython.com/pycharm-guide/) and [Thonny](https://realpython.com/python-thonny/), also allow you to run scripts from inside the environment. For example, in PyCharm, you can press `Ctrl`\+`R` on your keyboard to quickly run your appâs entry-point script.
Advanced code editors like [Visual Studio Code](https://code.visualstudio.com/docs) also allow you to run your scripts. In Visual Studio Code, you can press `Ctrl`\+`F5` to run the file thatâs currently active, for example.
To learn how to run Python scripts from your preferred IDE or code editor, check its specific documentation or take a quick look at the programâs GUI. Youâll quickly figure out the answer.
## How to Run Python Scripts From a File Manager
Running a script by double-clicking its icon in a [file manager](https://en.wikipedia.org/wiki/File_manager) is another way to run your Python scripts. You probably wonât use this option much in the development stage, but you may use it when you release your code for production.
In order to run your scripts with a double click, you must satisfy some conditions that will depend on your operating system.
Windows, for example, associates the extensions `.py` and `.pyw` with the programs `python.exe` and `pythonw.exe`, respectively. This allows you to run your scripts by double-clicking on their icons.
On Unix systems, youâll probably be able to run your scripts by double-clicking on them in your file manager. To achieve this, your script must have execution permissions, and youâll need to use the shebang trick that youâve already learned. Like on Windows, you may not see any output on-screen when it comes to command-line interface scripts.
The execution of scripts through a double click has several limitations and depends on many factors, such as the operating system, the file manager, execution permissions, and file associations. Still, you can consider this alternative a viable option for some utility scripts.
## Conclusion
Youâve acquired the knowledge and skills that you need for running Python scripts and code in several ways and in a variety of situations and development environments. The command line will be your best friend when you need to run production-ready scripts. During development, your IDE or code editor will provide the right option to run your code.
**In this tutorial, youâve learned how to:**
- Run Python scripts from the **command line** or **terminal** in your current OS
- Execute code in **interactive mode** using Pythonâs standard REPL
- Use your favorite **IDE** or **code editor** to run Python scripts during development
- Launch scripts and programs from your operating systemâs **file manager**
These skills are essential for you as a Python developer. Theyâll make your development process much faster, as well as more productive and flexible.
**Free Download:** [Get a sample chapter from Python Tricks: The Book](https://realpython.com/bonus/python-tricks-sample-pdf/) that shows you Pythonâs best practices with simple examples you can apply instantly to write more beautiful + Pythonic code.
***Take the Quiz:*** Test your knowledge with our interactive âHow to Run Your Python Scriptsâ quiz. Youâll receive a score upon completion to help you track your learning progress:
***
[](https://realpython.com/quizzes/run-python-scripts/)
**Interactive Quiz**
[How to Run Your Python Scripts](https://realpython.com/quizzes/run-python-scripts/)
One of the most important skills you need to build as a Python developer is to be able to run Python scripts and code. Test your understanding on how good you are with running your code.
## Frequently Asked Questions
Now that you have some experience with running Python scripts and code, you can use the questions and answers below to check your understanding and recap what youâve learned.
These FAQs are related to the most important concepts youâve covered in this tutorial. Click the *Show/Hide* toggle beside each question to reveal the answer.
**How do I run a Python script from the command line?**Show/Hide
To run a Python script from the command line, open a terminal or command prompt and type `python` followed by the path to your script file. For example, `python hello.py`. On Windows, you might also use `py` instead of `python`. If you see any errors, check that Python is added to your systemâs PATH variable.
**What is the difference between running Python code in script mode and running it in interactive mode?**Show/Hide
In script mode, you execute a file containing Python code using the Python interpreter, and the code runs sequentially. In interactive mode, you use the Python interpreter to run code directly, one statement at a time, often in a REPL (Read-Eval-Print Loop). This allows for immediate feedback and experimentation.
**Can I run a Python script by double-clicking it in a file manager?**Show/Hide
Yes. On Windows, you can double-click `.py` files to run them since theyâre associated with `python.exe`. On Unix systems, you need to ensure that the script has execution permissions and includes a shebang (`#!/usr/bin/env python3`) as the first line. However, this method may not display output for console applications.
**How can I execute a Python module using the command line?**Show/Hide
You can execute a Python module using the command line with the `-m` option. For example, `python -m module_name`. This runs the module as a script, provided itâs available in the Python module search path.
**What tools or environments are available to run Python scripts besides the command line?**Show/Hide
Besides the command line, you can run Python scripts using an IDE (Integrated Development Environment) like PyCharm or Thonny, a code editor like Visual Studio Code, or from an interactive session using the Python REPL. Each environment provides additional features to aid development and debugging.
Mark as Completed
Share
Recommended Course
[How to Run a Python Script](https://realpython.com/courses/running-python-scripts/) (24m)
đ Python Tricks đ
Get a short & sweet **Python Trick** delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

About **Leodanis Pozo Ramos**
[ ](https://realpython.com/team/lpozoramos/)
Leodanis is a self-taught Python developer, educator, and technical writer with over 10 years of experience.
[» More about Leodanis](https://realpython.com/team/lpozoramos/)
***
*Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:*
[](https://realpython.com/team/asantos/)
[Aldren](https://realpython.com/team/asantos/)
[](https://realpython.com/team/bweleschuk/)
[Brenda](https://realpython.com/team/bweleschuk/)
[](https://realpython.com/team/gahjelle/)
[Geir Arne](https://realpython.com/team/gahjelle/)
[](https://realpython.com/team/jjablonski/)
[Joanna](https://realpython.com/team/jjablonski/)
[](https://realpython.com/team/kfinegan/)
[Kate](https://realpython.com/team/kfinegan/)
[](https://realpython.com/team/kstratis/)
[Kyle](https://realpython.com/team/kstratis/)
Master Real-World Python Skills With Unlimited Access to Real Python

**Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:**
[Level Up Your Python Skills »](https://realpython.com/account/join/?utm_source=rp_article_footer&utm_content=run-python-scripts)
Master Real-World Python Skills
With Unlimited Access to Real Python

**Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:**
[Level Up Your Python Skills »](https://realpython.com/account/join/?utm_source=rp_article_footer&utm_content=run-python-scripts)
What Do You Think?
**Rate this article:**
[LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Frealpython.com%2Frun-python-scripts%2F)
[Twitter](https://twitter.com/intent/tweet/?text=Interesting%20Python%20article%20on%20%40realpython%3A%20How%20to%20Run%20Your%20Python%20Scripts%20and%20Code&url=https%3A%2F%2Frealpython.com%2Frun-python-scripts%2F)
[Bluesky](https://bsky.app/intent/compose?text=Interesting%20Python%20article%20on%20%40realpython.com%3A%20How%20to%20Run%20Your%20Python%20Scripts%20and%20Code%20https%3A%2F%2Frealpython.com%2Frun-python-scripts%2F)
[Facebook](https://facebook.com/sharer/sharer.php?u=https%3A%2F%2Frealpython.com%2Frun-python-scripts%2F)
[Email](mailto:?subject=Python%20article%20for%20you&body=How%20to%20Run%20Your%20Python%20Scripts%20and%20Code%20on%20Real%20Python%0A%0Ahttps%3A%2F%2Frealpython.com%2Frun-python-scripts%2F%0A)
Whatâs your \#1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.
**Commenting Tips:** The most useful comments are those written with the goal of learning from or helping out other students. [Get tips for asking good questions](https://realpython.com/python-beginner-tips/#tip-9-ask-good-questions) and [get answers to common questions in our support portal](https://support.realpython.com/).
***
Looking for a real-time conversation? Visit the [Real Python Community Chat](https://realpython.com/community/) or join the next [âOffice Hoursâ Live Q\&A Session](https://realpython.com/office-hours/). Happy Pythoning\!
Keep Learning
Related Topics: [basics](https://realpython.com/tutorials/basics/) [best-practices](https://realpython.com/tutorials/best-practices/) [devops](https://realpython.com/tutorials/devops/) [python](https://realpython.com/tutorials/python/)
Related Learning Paths:
- [DevOps With Python](https://realpython.com/learning-paths/python-devops/?utm_source=realpython&utm_medium=web&utm_campaign=related-learning-path&utm_content=run-python-scripts)
Related Courses:
- [How to Run a Python Script](https://realpython.com/courses/running-python-scripts/?utm_source=realpython&utm_medium=web&utm_campaign=related-course&utm_content=run-python-scripts)
Related Tutorials:
- [Python for Loops: The Pythonic Way](https://realpython.com/python-for-loop/?utm_source=realpython&utm_medium=web&utm_campaign=related-post&utm_content=run-python-scripts)
- [How to Use the OpenRouter API to Access Multiple AI Models via Python](https://realpython.com/openrouter-api/?utm_source=realpython&utm_medium=web&utm_campaign=related-post&utm_content=run-python-scripts)
- [How to Use Git: A Beginner's Guide](https://realpython.com/how-to-use-git/?utm_source=realpython&utm_medium=web&utm_campaign=related-post&utm_content=run-python-scripts)
- [Python Gains frozendict and Other Python News for March 2026](https://realpython.com/python-news-march-2026/?utm_source=realpython&utm_medium=web&utm_campaign=related-post&utm_content=run-python-scripts)
- [Automate Python Data Analysis With YData Profiling](https://realpython.com/ydata-profiling-eda/?utm_source=realpython&utm_medium=web&utm_campaign=related-post&utm_content=run-python-scripts)
## Keep reading Real Python by creating a free account or signing in:
[](https://realpython.com/account/signup/?intent=continue_reading&utm_source=rp&utm_medium=web&utm_campaign=rwn&utm_content=v1&next=%2Frun-python-scripts%2F)
[Continue »](https://realpython.com/account/signup/?intent=continue_reading&utm_source=rp&utm_medium=web&utm_campaign=rwn&utm_content=v1&next=%2Frun-python-scripts%2F)
Already have an account? [Sign-In](https://realpython.com/account/login/?next=/run-python-scripts/)
Almost there! Complete this form and click the button below to gain instant access:
Ă

"Python Tricks: The Book" â Free Sample Chapter (PDF)
##### Learn Python
- [Start Here](https://realpython.com/start-here/)
- [Learning Resources](https://realpython.com/search)
- [Code Mentor](https://realpython.com/mentor/)
- [Python Reference](https://realpython.com/ref/)
- [Python Cheat Sheet](https://realpython.com/cheatsheets/python/)
- [Support Center](https://support.realpython.com/)
##### Courses & Paths
- [Learning Paths](https://realpython.com/learning-paths/)
- [Quizzes & Exercises](https://realpython.com/quizzes/)
- [Browse Topics](https://realpython.com/tutorials/all/)
- [Live Courses](https://realpython.com/live/)
- [Books](https://realpython.com/books/)
##### Community
- [Podcast](https://realpython.com/podcasts/rpp/)
- [Newsletter](https://realpython.com/newsletter/)
- [Community Chat](https://realpython.com/community/)
- [Office Hours](https://realpython.com/office-hours/)
- [Learner Stories](https://realpython.com/learner-stories/)
##### Membership
- [Plans & Pricing](https://realpython.com/account/join/)
- [Team Plans](https://realpython.com/account/join-team/)
- [For Business](https://realpython.com/account/join-team/inquiry/)
- [For Schools](https://realpython.com/account/join-team/education-inquiry/)
- [Reviews](https://realpython.com/learner-stories/)
##### Company
- [About Us](https://realpython.com/about/)
- [Team](https://realpython.com/team/)
- [Mission & Values](https://realpython.com/mission/)
- [Editorial Guidelines](https://realpython.com/editorial-guidelines/)
- [Sponsorships](https://realpython.com/sponsorships/)
- [Careers](https://realpython.workable.com/)
- [Press Kit](https://realpython.com/media-kit/)
- [Merch](https://realpython.com/merch)
[Privacy Policy](https://realpython.com/privacy-policy/) â
[Terms of Use](https://realpython.com/terms/) â
[Security](https://realpython.com/security/) â
[Contact](https://realpython.com/contact/)
Happy Pythoning\!
© 2012â2026 DevCademy Media Inc. DBA Real Python. All rights reserved.
REALPYTHONâą is a trademark of DevCademy Media Inc.
[](https://realpython.com/)

You've blocked notifications | |||||||||
| Readable Markdown | Running Python scripts is essential for executing your code. You can run Python scripts from the command line using `python script.py`, directly by making files executable with shebangs on Unix systems, or through IDEs and code editors. Python also supports interactive execution through the standard REPL for testing code snippets.
This tutorial covers the most common practical approaches for running Python scripts across Windows, Linux, and macOS.
**By the end of this tutorial, youâll understand that:**
- The **`python`** command followed by a **script filename** executes the code from the **command line** on all operating systems.
- Script mode runs code from **files sequentially**, while interactive mode uses the **REPL** for execution and testing with immediate feedback.
- Unix systems require **executable permissions** and a **shebang line** like `#!/usr/bin/env python3` to run scripts directly as programs.
- The `python` commandâs `-m` option runs **Python modules** by searching `sys.path` rather than requiring file paths.
- IDEs like PyCharm and code editors like Visual Studio Code provide built-in options to **run scripts** from the environment interface.
To get the most out of this tutorial, you should know the basics of working with your operating systemâs [terminal](https://realpython.com/terminal-commands/) and file manager. Itâd also be beneficial to be familiar with a Python-friendly [IDE or code editor](https://realpython.com/python-ides-code-editors-guide/) and with the standard Python [REPL](https://realpython.com/python-repl/) (Read-Eval-Print Loop).
***Take the Quiz:*** Test your knowledge with our interactive âHow to Run Your Python Scriptsâ quiz. Youâll receive a score upon completion to help you track your learning progress:
***
[](https://realpython.com/quizzes/run-python-scripts/)
**Interactive Quiz**
[How to Run Your Python Scripts](https://realpython.com/quizzes/run-python-scripts/)
One of the most important skills you need to build as a Python developer is to be able to run Python scripts and code. Test your understanding on how good you are with running your code.
## What Scripts and Modules Are
In computing, the term **script** refers to a text file containing a logical sequence of orders that you can run to accomplish a specific task. These orders are typically expressed in a [scripting language](https://en.wikipedia.org/wiki/Scripting_language), which is a [programming language](https://en.wikipedia.org/wiki/Programming_language) that allows you to manipulate, customize, and automate tasks.
Scripting languages are usually [interpreted](https://en.wikipedia.org/wiki/Interpreter_\(computing\)) at [runtime](https://en.wikipedia.org/wiki/Runtime_\(program_lifecycle_phase\)) rather than [compiled](https://en.wikipedia.org/wiki/Compiler). So, scripts are typically run by an [interpreter](https://realpython.com/ref/glossary/interpreter/), which is responsible for executing each order in a sequence.
[Python](https://realpython.com/ref/glossary/python/) is an interpreted language. Because of that, Python programs are commonly called scripts. However, this terminology isnât completely accurate because Python programs can be way more complex than a simple, sequential script.
In general, a [file](https://realpython.com/ref/glossary/text-file/) containing executable Python [code](https://realpython.com/ref/glossary/source-code/) is called a scriptâor an **entry-point script** in more complex applicationsâwhich is a common term for a top-level **program**. On the other hand, a file containing Python code thatâs designed to be [imported](https://realpython.com/python-import/) and used from another Python file is called a [**module**](https://realpython.com/ref/glossary/module/).
So, the main difference between a [module](https://realpython.com/python-modules-packages/) and a script is that modules store **importable code** while scripts hold **executable code**.
In the following sections, youâll learn how to run Python scripts, programs, and code in general. To kick things off, youâll start by learning how to run them from your operating systemâs command line or terminal.
## How to Run Python Scripts From the Command Line
In Python programming, youâll write programs in plain text files. By convention, files containing Python code use the `.py` extension, and thereâs no distinction between scripts or executable programs and modules. All of them will use the same extension.
To create a Python script, you can use any Python-friendly [code editor or IDE](https://realpython.com/python-ides-code-editors-guide/) (integrated development environment). To keep moving forward in this tutorial, youâll need to create a basic script, so fire up your favorite text editor and create a new `hello.py` file containing the following code:
This is the classic `"Hello, World!"` program in Python. The executable code consists of a call to the built-in [`print()`](https://realpython.com/python-print/) function that displays the `"Hello, World!"` message on your screen.
With this small program in place, youâre ready to learn different ways to run it. Youâll start by running the program from your command line, which is arguably the most commonly used approach to running scripts.
### Using the `python` Command
To run Python scripts with the `python` command, you need to open a command-line window and type in the word `python` followed by the path to your target script:
- [Windows](https://realpython.com/run-python-scripts/#windows-1)
- [Linux + macOS](https://realpython.com/run-python-scripts/#linux-macos-1)
After you press `Enter`, youâll see the phrase `Hello, World!` on your screen. If the previous command doesnât work right, then you may need to check if Python is in your systemâs [`PATH`](https://realpython.com/add-python-to-path/). You can also check where you saved `hello.py`.
Thatâs it! Youâve run your first script! Note that on Windows, you also have the option of using the `py` launcher, which triggers the `py.exe` launcher for console applications. This is the most basic and practical way to run Python scripts.
A useful feature of a terminal or [shell application](https://en.wikipedia.org/wiki/Unix_shell) is that you can redirect the output of your commands using a straightforward syntax. This feature may be useful in those situations where you have a Python program that can generate a long output, and youâd like to save it to a file for later analysis.
In these scenarios, you can do something like the following:
In this command, the `>` symbol tells the shell to redirect the output of your command to the `output.txt` file, rather than to the standard system output, your screen. This process is commonly known as [redirection](https://en.wikipedia.org/wiki/Redirection_\(computing\)), and it works on both Windows and [Unix-like](https://en.wikipedia.org/wiki/Unix) systems, such as Linux and macOS.
If the output file doesnât exist, then the shell automatically creates it. On the other hand, if the file already exists, then the shell overwrites its old content with the new output.
Finally, if you want to add the output of consecutive executions to the end of `output.txt`, then you can use two angle brackets (`>>`) instead of one:
Now, the shell app will append the current output to the end of `output.txt`. Youâll end up with a file containing the phrase `"Hello, World!"` twice.
### Using the Scriptâs Filename Directly
On Windows, you can also run Python scripts by entering the name of the file containing the executable code at the command line:
Once youâve written the path to your script and pressed `Enter`, youâll note that a new terminal window appears on your screen for a few seconds, showing the script output. This is possible because Windows associates `.py` and `.pyw` files to `python.exe` and `pythonw.exe`, respectively.
This way of running Python scripts on Windows may be annoying because the code runs in a new terminal window that automatically closes after the execution ends. In most cases, you wonât be able to check the programâs output.
On Linux and macOS, you can also run your scripts directly. However, things are a bit different, and you need some additional setup steps. Go ahead and run the following command:
- [Linux](https://realpython.com/run-python-scripts/#linux-2)
- [macOS](https://realpython.com/run-python-scripts/#macos-2)
Unix systems prioritize security, which means that you canât go around executing any file as a program. So, you get a permission denied error when you try to run `hello.py` directly. To fix this issue, you need to explicitly tell the system that the file is executable. To do this, you can use the `chmod` command:
After running this command, your `hello.py` file will be executable. However, thatâs not enough for the script to run properly:
Why are you getting another error now? The problem is that your operating system (OS) doesnât know which program to use for running your script and is trying to run it with the shell itself. You can fix that by making a small addition to your `hello.py` file:
Youâve added a new line at the beginning of `hello.py`. It now starts with a Unix-style [shebang](https://realpython.com/python-shebang/), which is a special kind of [comment](https://realpython.com/python-comments-guide/) that you can include in your scripts to tell the operating system which program to use for running the content of this file. In this case, you tell the OS to use Python.
Now you can run the script directly from your command line:
Wow! That was a long road! However, the effort was worth it. Now when you create a Python script to automate tasks in a Unix operating system, you know how to make it executable and run it from your command line.
### Running Modules With the `-m` Option
The `python` command has a series of [command-line options](https://realpython.com/python-command-line-arguments/) that can be useful in specific situations. For example, if you want to run a Python module, then you can use the command `python -m <module-name>`. The `-m` option searches Pythonâs [module search path](https://docs.python.org/3/tutorial/modules.html#the-module-search-path), `sys.path`, for the module name and runs its content:
In this example, you run the `hello.py` file as a module. This is possible because Python automatically adds the current directory to its `sys.path` [list](https://realpython.com/ref/builtin-types/list/). Note that the `module-name` argument needs to be the name of a module object, not a file name. In other words, you donât include the `.py` suffix.
If the target module isnât in `sys.path`, then you get an error:
In this example, the `missing` name isnât in the `sys.path` list, so Python isnât able to execute it, and therefore it returns an error.
## How to Run Python Code Interactively
Running scripts isnât the only way to run Python code. Because Python is an interpreted language, you can use the interpreter to run code interactively. When you run the `python` command without arguments, you start a new interactive session, or [REPL](https://realpython.com/python-repl/) (Read-Eval-Print Loop). In there, you can run any Python code and get immediate feedback about how the code works.
In the following sections, youâll learn the basics of the Python interpreter and how to run code in it. This knowledge will be valuable for you, especially in those situations where you need to quickly test a small piece of Python code.
### Getting to Know the Python Interpreter
Python is a high-level programming language with a clean and readable syntax. Python and its wide ecosystem of [packages](https://realpython.com/ref/glossary/package/) and libraries can boost your productivity in a [variety of fields](https://realpython.com/what-can-i-do-with-python/). The name Python also refers to a piece of software called the **interpreter**, which is the program that allows you to run Python code.
The interpreter is a layer of software that works between your program and your computer hardware to get your code running. Depending on the Python [implementation](https://www.python.org/download/alternatives/) that you use, the interpreter can be a program written in:
- [C](https://realpython.com/c-for-python-programmers/), like [CPython](https://realpython.com/cpython-source-code-guide/), which is the core implementation of the language
- Python itself, like [PyPy](https://realpython.com/pypy-faster-python/), which is a [fast](http://speed.pypy.org/) implementation with a [just-in-time (JIT) compiler](https://en.wikipedia.org/wiki/Just-in-time_compilation)
- [Java](https://realpython.com/oop-in-python-vs-java/), like [Jython](http://www.jython.org/index.html), which can take advantage of the Java ecosystem
- .NET, like [IronPython](http://ironpython.net/), which uses the .NET ecosystem
Whatever interpreter you use, the code that you write will run in this program. Therefore, the first condition to be able to run scripts and code is to have the interpreter correctly [installed](https://realpython.com/installing-python/) on your operating system.
The Python interpreter can run code in two different modes:
1. [Script](https://realpython.com/run-python-scripts/), or program
2. [Interactive](https://realpython.com/interacting-with-python/), or REPL
In **script mode**, you use the interpreter to run a source file as an executable program, as you learned in the previous section. In this case, Python loads the file content and runs the code line by line, following the programâs execution flow.
Alternatively, **interactive mode** is when you launch the interpreter and use it as a platform to run code that you type in directly. This mode is pretty useful for learning Python as well as for developing, testing, and [debugging](https://realpython.com/ref/glossary/debugging/) your applications.
### Running Python Code Interactively
Interactive sessions are a widely used tool for running Python code. To start a Python interactive session, or REPL, open a command-line window, type in the `python` command, and then press `Enter`.
These steps will take you into the Python interpreter, which looks something like the following:
- [Windows](https://realpython.com/run-python-scripts/#windows-3)
- [Linux](https://realpython.com/run-python-scripts/#linux-3)
- [macOS](https://realpython.com/run-python-scripts/#macos-3)
The standard primary prompt for the interactive mode consists of three right angle brackets, `>>>`. So, as soon as you see these characters, youâll know that youâre in.
The Python interpreter is an interactive way to talk to your computer using the language. Itâs like live chat. Itâs also known as the REPL because it goes through four steps that run under the hood:
1. **Reading** your input, which consists of Python code as [expressions](https://docs.python.org/3/glossary.html#term-expression) and [statements](https://docs.python.org/3/glossary.html#term-statement)
2. **Evaluating** your Python code, which generates a result or causes [side effects](https://en.wikipedia.org/wiki/Side_effect_\(computer_science\))
3. **Printing** any output so that you can check your codeâs results and get immediate feedback
4. **Looping** back to step one to continue the interaction
This Python feature is a powerful tool that youâll wind up needing in your coding adventure, especially when youâre learning the language or when youâre in the early stages of a development process.
Once youâve started a REPL session, you can write and run Python code as you wish. The only drawback is that when you close the session, your code will be gone. This is another difference between the script and interactive modes: *scripts are persistent*.
When you work interactively, Python evaluates and executes every expression and statement immediately:
An interactive session allows you to test every piece of code immediately. Thatâs why this tool is an awesome development helper and an excellent space to experiment with the language and test ideas on the fly.
To leave interactive mode and jump back to the system shell, you can use one of the following options:
- Executing the built-in `quit()` or `exit()` functions, which are plain commands (`quit` and `exit`) in [Python 3.13](https://realpython.com/python313-new-features/) or later
- Pressing the `Ctrl`\+`Z` and `Enter` key combination on Windows, or the `Ctrl`\+`D` combination on Unix systems, such as Linux and macOS
Go ahead and give the Python REPL a try. Youâll see that itâs a great development tool that you must keep in your tool kit.
## How to Run Scripts From Python Code
You can also run Python scripts and modules from an interactive session or from a `.py` file. This option opens a variety of possibilities. In the following sections, youâll explore a few tools and techniques that will allow you to run scripts and code from Python code.
### Taking Advantage of `import` Statements
When you [import a module](https://realpython.com/absolute-vs-relative-python-imports/) from another module, script, or interactive session, what really happens is that Python loads its contents for later access and use. The interesting point is that the [`import`](https://realpython.com/ref/keywords/import/) statement runs any executable code in the imported module.
When the module contains only [class](https://realpython.com/python-classes/), function, [variable](https://realpython.com/python-variables/), and [constant](https://realpython.com/python-constants/) definitions, you probably wonât be aware that the code was run. However, when the module includes calls to functions, [methods](https://realpython.com/ref/glossary/method/), or other [statements](https://realpython.com/ref/glossary/statement/) that generate visible results, then youâll witness its execution.
This provides you with another approach to run scripts:
Youâll note that `import` runs the code only once per session. After you first import a module, successive imports do nothing, even if you modify the content of the module. This is because `import` operations are expensive, and Python takes some extra steps to optimize overall performance:
These two imports do nothing because Python knows that the `hello` module was already imported. Therefore, Python skips the import. This behavior may seem annoying, especially when youâre working on a module and trying to test your changes in an interactive session. However, itâs an intentional optimization.
### Using the `importlib` Standard-Library Module
In the Python [standard library](https://docs.python.org/3/library/index.html), you can find the [`importlib`](https://realpython.com/ref/stdlib/importlib/) module. This module provides the [`import_module()`](https://docs.python.org/3/library/importlib.html#importlib.import_module) function, which allows you to programmatically import modules.
With `import_module()`, you can emulate an `import` operation and, therefore, execute any module or script. Take a look at this example:
The `import_module()` function imports a module programmatically using its name. This action runs any executable code in the target module. Thatâs why you get `Hello, World!` on your screen.
You already know that once youâve imported a module for the first time, you wonât be able to import it again using another `import` statement. If you want to reload the module and run it once again, then you can use the [`reload()`](https://docs.python.org/3/library/importlib.html#importlib.reload) function, which forces the interpreter to import the module again:
An important point to note here is that the argument of `reload()` has to be the name of a module object, not a [string](https://realpython.com/python-strings/). So, to use `reload()` successfully, you need to provide a module thatâs already imported.
### Leveraging the Power of the Built-in `exec()` Function
So far, youâve learned about some handy ways to run Python scripts. In this section, youâll learn how to do that by using the built-in [`exec()`](https://realpython.com/python-exec/) function, which supports the dynamic execution of Python code.
The [`exec()`](https://realpython.com/ref/builtin-functions/exec/) function provides an alternative way to run your scripts from inside your code:
In this example, you use the [`with` statement](https://realpython.com/python-with-statement/) to open the `hello.py` file for reading. Then, you read the fileâs content with the `.read()` method. This method returns a [string](https://realpython.com/ref/builtin-types/str/) that you pass to `exec()` for execution.
You must be careful when using the `exec()` function because it implies some important security risks, especially if youâre using it for executing external code from untrusted sources. To learn more about this function, check out [Pythonâs `exec()`: Execute Dynamically Generated Code](https://realpython.com/python-exec/).
## How to Run Python Scripts on IDEs and Code Editors
For developing a large and complex application, you should use an [integrated development environment (IDE)](https://realpython.com/ref/glossary/ide/) or an advanced text editor that incorporates programmer-friendly features.
Most of these programs have options that allow you to run your scripts from inside the environment itself. Itâs common for them to include a *Run* or *Build* action, which is usually available from the toolbar or from the main menu.
Pythonâs standard distribution comes with [IDLE](https://realpython.com/python-idle/) as its default IDE. You can use this program to write, debug, modify, and run your modules and scripts. Other IDEs, such as [PyCharm](https://realpython.com/pycharm-guide/) and [Thonny](https://realpython.com/python-thonny/), also allow you to run scripts from inside the environment. For example, in PyCharm, you can press `Ctrl`\+`R` on your keyboard to quickly run your appâs entry-point script.
Advanced code editors like [Visual Studio Code](https://code.visualstudio.com/docs) also allow you to run your scripts. In Visual Studio Code, you can press `Ctrl`\+`F5` to run the file thatâs currently active, for example.
To learn how to run Python scripts from your preferred IDE or code editor, check its specific documentation or take a quick look at the programâs GUI. Youâll quickly figure out the answer.
## How to Run Python Scripts From a File Manager
Running a script by double-clicking its icon in a [file manager](https://en.wikipedia.org/wiki/File_manager) is another way to run your Python scripts. You probably wonât use this option much in the development stage, but you may use it when you release your code for production.
In order to run your scripts with a double click, you must satisfy some conditions that will depend on your operating system.
Windows, for example, associates the extensions `.py` and `.pyw` with the programs `python.exe` and `pythonw.exe`, respectively. This allows you to run your scripts by double-clicking on their icons.
On Unix systems, youâll probably be able to run your scripts by double-clicking on them in your file manager. To achieve this, your script must have execution permissions, and youâll need to use the shebang trick that youâve already learned. Like on Windows, you may not see any output on-screen when it comes to command-line interface scripts.
The execution of scripts through a double click has several limitations and depends on many factors, such as the operating system, the file manager, execution permissions, and file associations. Still, you can consider this alternative a viable option for some utility scripts.
## Conclusion
Youâve acquired the knowledge and skills that you need for running Python scripts and code in several ways and in a variety of situations and development environments. The command line will be your best friend when you need to run production-ready scripts. During development, your IDE or code editor will provide the right option to run your code.
**In this tutorial, youâve learned how to:**
- Run Python scripts from the **command line** or **terminal** in your current OS
- Execute code in **interactive mode** using Pythonâs standard REPL
- Use your favorite **IDE** or **code editor** to run Python scripts during development
- Launch scripts and programs from your operating systemâs **file manager**
These skills are essential for you as a Python developer. Theyâll make your development process much faster, as well as more productive and flexible.
***Take the Quiz:*** Test your knowledge with our interactive âHow to Run Your Python Scriptsâ quiz. Youâll receive a score upon completion to help you track your learning progress:
***
[](https://realpython.com/quizzes/run-python-scripts/)
**Interactive Quiz**
[How to Run Your Python Scripts](https://realpython.com/quizzes/run-python-scripts/)
One of the most important skills you need to build as a Python developer is to be able to run Python scripts and code. Test your understanding on how good you are with running your code.
## Frequently Asked Questions
Now that you have some experience with running Python scripts and code, you can use the questions and answers below to check your understanding and recap what youâve learned.
These FAQs are related to the most important concepts youâve covered in this tutorial. Click the *Show/Hide* toggle beside each question to reveal the answer.
To run a Python script from the command line, open a terminal or command prompt and type `python` followed by the path to your script file. For example, `python hello.py`. On Windows, you might also use `py` instead of `python`. If you see any errors, check that Python is added to your systemâs PATH variable.
In script mode, you execute a file containing Python code using the Python interpreter, and the code runs sequentially. In interactive mode, you use the Python interpreter to run code directly, one statement at a time, often in a REPL (Read-Eval-Print Loop). This allows for immediate feedback and experimentation.
Yes. On Windows, you can double-click `.py` files to run them since theyâre associated with `python.exe`. On Unix systems, you need to ensure that the script has execution permissions and includes a shebang (`#!/usr/bin/env python3`) as the first line. However, this method may not display output for console applications.
You can execute a Python module using the command line with the `-m` option. For example, `python -m module_name`. This runs the module as a script, provided itâs available in the Python module search path.
Besides the command line, you can run Python scripts using an IDE (Integrated Development Environment) like PyCharm or Thonny, a code editor like Visual Studio Code, or from an interactive session using the Python REPL. Each environment provides additional features to aid development and debugging. | |||||||||
| ML Classification | ||||||||||
| ML Categories |
Raw JSON{
"/Computers_and_Electronics": 988,
"/Computers_and_Electronics/Programming": 951,
"/Computers_and_Electronics/Programming/Scripting_Languages": 914
} | |||||||||
| ML Page Types |
Raw JSON{
"/Article": 998,
"/Article/Tutorial_or_Guide": 546
} | |||||||||
| ML Intent Types |
Raw JSON{
"Informational": 999
} | |||||||||
| Content Metadata | ||||||||||
| Language | en | |||||||||
| Author | Real Python | |||||||||
| Publish Time | not set | |||||||||
| Original Publish Time | 2019-02-18 06:40:36 (7 years ago) | |||||||||
| Republished | No | |||||||||
| Word Count (Total) | 5,534 | |||||||||
| Word Count (Content) | 3,791 | |||||||||
| Links | ||||||||||
| External Links | 40 | |||||||||
| Internal Links | 153 | |||||||||
| Technical SEO | ||||||||||
| Meta Nofollow | No | |||||||||
| Meta Noarchive | No | |||||||||
| JS Rendered | Yes | |||||||||
| Redirect Target | null | |||||||||
| Performance | ||||||||||
| Download Time (ms) | 230 | |||||||||
| TTFB (ms) | 209 | |||||||||
| Download Size (bytes) | 31,830 | |||||||||
| Shard | 71 (laksa) | |||||||||
| Root Hash | 13351397557425671 | |||||||||
| Unparsed URL | com,realpython!/run-python-scripts/ s443 | |||||||||