Basics Intermediate Advanced
aialgorithmsapibest-practicescareercommunitydatabasesdata-sciencedata-structuresdata-vizdevopsdjangodockereditorsflaskfront-endgamedevguimachine-learningnewsnumpyprojectspythonstdlibtestingtoolsweb-devweb-scraping
Recommended Course

How to Run a Python Script
24m · 8 lessons

How to Run Your Python Scripts and Code
Table of Contents
Recommended Course
Running Python scripts is essential for executing your code. You can run Python scripts from the command line usingpython 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
pythoncommand followed by ascript filename executes the code from thecommand line on all operating systems. - Script mode runs code fromfiles sequentially, while interactive mode uses theREPL for execution and testing with immediate feedback.
- Unix systems requireexecutable permissions and ashebang line like
#!/usr/bin/env python3to run scripts directly as programs. - The
pythoncommand’s-moption runsPython modules by searchingsys.pathrather than requiring file paths. - IDEs like PyCharm and code editors like Visual Studio Code provide built-in options torun scripts from the environment interface.
To get the most out of this tutorial, you should know the basics of working with your operating system’sterminal and file manager. It’d also be beneficial to be familiar with a Python-friendlyIDE or code editor and with the standard PythonREPL (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. You’ll receive a score upon completion to help you track your learning progress:
Interactive Quiz
How to Run Your Python ScriptsOne 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 termscript 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 ascripting language, which is aprogramming language that allows you to manipulate, customize, and automate tasks.
Scripting languages are usuallyinterpreted atruntime rather thancompiled. So, scripts are typically run by aninterpreter, 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, afile containing executable Pythoncode is called a script—or anentry-point script in more complex applications—which is a common term for a top-levelprogram. On the other hand, a file containing Python code that’s designed to beimported and used from another Python file is called amodule.
So, the main difference between amodule and a script is that modules storeimportable code while scripts holdexecutable code.
Note: Importable code is code that defines something but doesn’t perform a specific action. Some examples includefunction andclass definitions. In contrast, executable code is code that performs specific actions. Some examples includefunction calls,loops, andconditionals.
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: OnWindows systems, the extension can also be.pyw for those applications that should use thepythonw.exe launcher.
To create a Python script, you can use any Python-friendlycode 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 newhello.py file containing the following code:
hello.pyprint("Hello, World!")This is the classic"Hello, World!" program in Python. The executable code consists of a call to the built-inprint() 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 thepython Command
To run Python scripts with thepython command, you need to open a command-line window and type in the wordpython followed by the path to your target script:
PS>python.\hello.pyHello, World!PS>py.\hello.pyHello, World!$python./hello.pyHello, World!After you pressEnter, you’ll see the phraseHello, World! on your screen. If the previous command doesn’t work right, then you may need to check if Python is in your system’sPATH. You can also check where you savedhello.py.
Note: In some Linux distributions and probably in some macOS versions, you may need to use thepython3 command instead ofpython.
That’s it! You’ve run your first script! Note that on Windows, you also have the option of using thepy launcher, which triggers thepy.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 theSearch 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 typingTerminal and pressingEnter 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 pressingCtrl+Alt+T.
To learn more about using the command line or terminal, check outThe Terminal: First Steps and Useful Commands.
A useful feature of a terminal orshell 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:
$pythonhello.py>output.txtIn this command, the> symbol tells the shell to redirect the output of your command to theoutput.txt file, rather than to the standard system output, your screen. This process is commonly known asredirection, and it works on both Windows andUnix-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 ofoutput.txt, then you can use two angle brackets (>>) instead of one:
$pythonhello.py>>output.txtNow, the shell app will append the current output to the end ofoutput.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:
PS> .\hello.pyOnce you’ve written the path to your script and pressedEnter, 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 topython.exe andpythonw.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:
$./hello.pybash: ./hello.py: Permission denied$./hello.pyzsh: permission denied: ./hello.pyUnix 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 runhello.py directly. To fix this issue, you need to explicitly tell the system that the file is executable. To do this, you can use thechmod command:
$chmod+xhello.pyAfter running this command, yourhello.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 yourhello.py file:
hello.py#!/usr/bin/env python3print("Hello, World!")You’ve added a new line at the beginning ofhello.py. It now starts with a Unix-styleshebang, which is a special kind ofcomment 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 theenv command to find out where the interpreter lives.
Now you can run the script directly from your command line:
$./hello.pyHello, 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
Thepython command has a series ofcommand-line options that can be useful in specific situations. For example, if you want to run a Python module, then you can use the commandpython -m <module-name>. The-m option searches Python’smodule search path,sys.path, for the module name and runs its content:
$python-mhelloHello, World!In this example, you run thehello.py file as a module. This is possible because Python automatically adds the current directory to itssys.pathlist. Note that themodule-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 thecommand-line interface (CLI) ofstandard-library modules, such aspip,venv,http.server, andzipfile.
If the target module isn’t insys.path, then you get an error:
$python-mmissing.../python: No module named missingIn this example, themissing name isn’t in thesys.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 thepython command without arguments, you start a new interactive session, orREPL (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 ofpackages and libraries can boost your productivity in avariety of fields. The name Python also refers to a piece of software called theinterpreter, 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 Pythonimplementation that you use, the interpreter can be a program written in:
- C, likeCPython, which is the core implementation of the language
- Python itself, likePyPy, which is afast implementation with ajust-in-time (JIT) compiler
- Java, likeJython, which can take advantage of the Java ecosystem
- .NET, likeIronPython, 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 correctlyinstalled on your operating system.
The Python interpreter can run code in two different modes:
- Script, or program
- Interactive, or REPL
Inscript 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, anddebugging 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 thepython command, and then pressEnter.
These steps will take you into the Python interpreter, which looks something like the following:
PS>pythonPython 3.14.3 (tags/v3.14.3:323c59a, Feb 3 2026, 16:04:56) ... on win32Type "help", "copyright", "credits" or "license" for more information.>>>$pythonPython 3.14.3 (main, Feb 3 2026, 13:58:44) ... on linuxType "help", "copyright", "credits" or "license" for more information.>>>$pythonPython 3.14.3 (v3.14.3:323c59a5e34, Feb 3 2026, 11:41:37) ... on darwinType "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.
Note: The standard REPL also has a secondary prompt that consists of three periods (...). This prompt appears when you add indented lines to acompound 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 asexpressions andstatements
- Evaluating your Python code, which generates a result or causesside 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:
>>>print("Hello, World!")Hello, World!>>>2+57>>>print("Welcome to Real Python!")Welcome to Real 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()orexit()functions, which are plain commands (quitandexit) inPython 3.13 or later - Pressing theCtrl+Z andEnter key combination on Windows, or theCtrl+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 ofimport Statements
When youimport 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 theimport statement runs any executable code in the imported module.
When the module contains onlyclass, function,variable, andconstant definitions, you probably won’t be aware that the code was run. However, when the module includes calls to functions,methods, or otherstatements that generate visible results, then you’ll witness its execution.
This provides you with another approach to run scripts:
>>>importhelloHello, World!You’ll note thatimport 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 becauseimport operations are expensive, and Python takes some extra steps to optimize overall performance:
>>>importhello# Do nothing>>>importhello# Do nothing againThese two imports do nothing because Python knows that thehello 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 theimportlib Standard-Library Module
In the Pythonstandard library, you can find theimportlib module. This module provides theimport_module() function, which allows you to programmatically import modules.
Withimport_module(), you can emulate animport operation and, therefore, execute any module or script. Take a look at this example:
>>>importimportlib>>>importlib.import_module("hello")Hello, World!<module 'hello' from '/Users/username/hello.py'>Theimport_module() function imports a module programmatically using its name. This action runs any executable code in the target module. That’s why you getHello, 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 anotherimport statement. If you want to reload the module and run it once again, then you can use thereload() function, which forces the interpreter to import the module again:
>>>importhelloHello, World!>>>importimportlib>>>importlib.reload(hello)Hello, World!<module 'hello' from '/Users/username/hello.py'>An important point to note here is that the argument ofreload() has to be the name of a module object, not astring. So, to usereload() successfully, you need to provide a module that’s already imported.
Leveraging the Power of the Built-inexec() 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-inexec() function, which supports the dynamic execution of Python code.
Theexec() function provides an alternative way to run your scripts from inside your code:
>>>withopen("hello.py")ashello:...exec(hello.read())...Hello, World!In this example, you use thewith statement to open thehello.py file for reading. Then, you read the file’s content with the.read() method. This method returns astring that you pass toexec() for execution.
You must be careful when using theexec() 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 outPython’sexec(): Execute Dynamically Generated Code.
How to Run Python Scripts on IDEs and Code Editors
For developing a large and complex application, you should use anintegrated 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 aRun orBuild action, which is usually available from the toolbar or from the main menu.
Python’s standard distribution comes withIDLE as its default IDE. You can use this program to write, debug, modify, and run your modules and scripts. Other IDEs, such asPyCharm andThonny, also allow you to run scripts from inside the environment. For example, in PyCharm, you can pressCtrl+R on your keyboard to quickly run your app’s entry-point script.
Advanced code editors likeVisual Studio Code also allow you to run your scripts. In Visual Studio Code, you can pressCtrl+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 afile 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 programspython.exe andpythonw.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 thecommand line orterminal in your current OS
- Execute code ininteractive mode using Python’s standard REPL
- Use your favoriteIDE orcode editor to run Python scripts during development
- Launch scripts and programs from your operating system’sfile 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 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:
Interactive Quiz
How to Run Your Python ScriptsOne 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 theShow/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 typepython followed by the path to your script file. For example,python hello.py. On Windows, you might also usepy instead ofpython. 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 withpython.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.
Recommended Course
🐍 Python Tricks 💌
Get a short & sweetPython Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

AboutLeodanis Pozo Ramos
Leodanis is a self-taught Python developer, educator, and technical writer with over 10 years of experience.
» More about LeodanisMasterReal-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:
MasterReal-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:
What Do You Think?
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 andget answers to common questions in our support portal.
Looking for a real-time conversation? Visit theReal Python Community Chat or join the next“Office Hours” Live Q&A Session. Happy Pythoning!
Keep Learning
Related Topics:basicsbest-practicesdevopspython
Related Learning Paths:
Related Courses:
Related Tutorials:
Keep reading Real Python by creating a free account or signing in:
Already have an account?Sign-In







