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).
Free Download: Get a sample chapter from Python Tricks: The Book 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. Upon completion you will receive a score so you can track your learning progress over time:
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.
Note: Importable code is code that defines something but doesn’t perform a specific action. Some examples include function and class definitions. In contrast, executable code is code that performs specific actions. Some examples include function calls, loops, and conditionals.
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.
Note: On 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 (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:
# 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:
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.
Note: In some Linux distributions and probably in some macOS versions, you may need to use the python3 command instead of simply python.
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.
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 bar. Once you’ve launched this program, you can start running commands in it.
-
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.
-
On macOS, you can access the system terminal from the Launchpad by typing Terminal and pressing Enter when the app appears.
To learn more about using the command line or terminal, check out The Terminal: First Steps and Useful Commands.
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:
$ 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:
$ 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:
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:
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:
$ 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:
$ ./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:
#!/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.
Note: You’ll have at least two different ways to specify the path to the interpreter in the shebang comment:
- Provide the absolute path to the interpreter, like in
#!/usr/bin/python3 - Use the operating system’s
envcommand, 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:
$ ./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:
$ 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.
Note: Using the -m option is common practice when you need to use the command-line interface (CLI) of standard-library modules, such as pip, venv, http.server, and zipfile.
If the target module isn’t in sys.path, then you get an error:
$ 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:
- 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, 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:
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, 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:
- 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 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:
>>> 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()orexit()functions - Pressing the Ctrl+Z and