How to Run Your Python Scripts

How to Run Your Python Scripts and Code

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Running Python Scripts

A Python script or program is a file containing executable Python code. Being able to run Python scripts and code is probably the most important skill that you need as a Python developer. By running your code, you’ll know if it works as planned. You’ll also be able to test and debug the code to fix errors and issues. Ultimately, you write code in order to run it and accomplish tasks.

In this tutorial, you’ll learn about some of the techniques for running Python scripts and code. The technique that you’ll use in each situation will depend on your environment, platform, needs, and skills.

In this tutorial, you’ll learn how to:

  • Run Python scripts from your operating system’s command line or terminal
  • Execute Python code and scripts in interactive mode using the standard REPL
  • Use your favorite IDE or code editor to run your Python scripts
  • Fire up your scripts and programs from your operating system’s file manager

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 for you 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 some kind of 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:

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() function that displays the "Hello, World!" message on your screen.

With this small program ready, 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 PowerShell
PS> python .\hello.py
Hello, World!

PS> py .\hello.py
Hello, World!
Shell
$ python ./hello.py
Hello, World!

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 command, which triggers the py.exe launcher for console applications. This is the most basic and practical way to run Python scripts.

A cool 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 situations, 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, 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:

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.

Using the Script’s Filename Directly

On Windows, you can also run Python scripts by simply 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 here, and you need some setup steps. Go ahead and run the following command:

Shell
$ ./hello.py
bash: ./hello.py: Permission denied
Shell
$ ./hello.py
zsh: permission denied: ./hello.py

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
$ ./hello.py
./hello.py: line 1: syntax error near unexpected token `"Hello, World!"'
./hello.py: line 1: `print("Hello, World!")'

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
#!/usr/bin/env python3

print("Hello, World!")

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:

Shell
$ ./hello.py
Hello, World!

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:

Shell
$ python -m hello
Hello, World!

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:

Shell
$ python -m missing
.../python: No module named missing

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 pretty 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:

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:

  1. Script, or program
  2. Interactive, or REPL

In script mode, you use the interpreter to run a source file as an executable program, just like 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 PowerShell
PS> python
Python 3.11.5 (tags/v3.11.5:cce6ba9, Aug 24 2023, 14:38:34) [MSC v.1936 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
Shell
$ python
Python 3.11.5 (main, Sep 13 2023, 18:12:18) [GCC 11.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
Shell
$ python
Python 3.11.5 (main, Aug 31 2023, 19:03:43) [Clang 14.0.3 (clang-1403.0.22.14.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>

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 and statements
  2. Evaluating your Python code, which generates a result or causes side effects
  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 feature of Python is a powerful tool that you’ll wind up needing in your Python 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
>>> print("Hello, World!")
Hello, World!

>>> 2 + 5
7

>>> print("Welcome to Real Python!")
Welcome to Real Python!

An interactive session will allow you to test every piece of code that you execute. 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
  • 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 option to run scripts:

Python
>>> import hello
Hello, World!

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
>>> import hello  # Do nothing
>>> import hello  # Do nothing again

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:

Python
>>> import importlib
>>> importlib.import_module("hello")
Hello, World!
<module 'hello' from '/home/username/hello.py'>

The import_module() function imports a module, bringing its name to your current namespace. It also runs any executable code that the target module contains. 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:

Python
>>> import hello
Hello World!

>>> import importlib
>>> importlib.reload(hello)
Hello World!
<module 'hello' from '/home/username/hello.py'>

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:

Python
>>> with open("hello.py") as hello:
...     exec(hello.read())
...
Hello, World!

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 running external code. 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 programs 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 the 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 and Sublime Text 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 on 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 production-ready scripts and programs.

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.

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Running Python Scripts

🐍 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.

Python Tricks Dictionary Merge

About Leodanis Pozo Ramos

Leodanis is an industrial engineer who loves Python and software development. He's a self-taught Python developer with 6+ years of experience. He's an avid technical writer with a growing number of articles published on Real Python and other sites.

» More about Leodanis

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:

Master Real-World Python Skills With Unlimited Access to Real Python

Locked learning resources

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Level Up Your Python Skills »

Master Real-World Python Skills
With Unlimited Access to Real Python

Locked learning resources

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Level Up Your Python Skills »

What Do You Think?

Rate this article:

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 and get answers to common questions in our support portal.


Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session. Happy Pythoning!