How to Run a Python Script: 6 Top Methods Explained

by | Python

A crucial operation you need to be aware of when programming is to run a Python script.

Although this seems like a simple operation, most beginners often face difficulty when running scripts.

In this article, we will guide you through the process of running scripts in Python using different methods and environments.

To run a Python script, you must:

  1. Open a Terminal or Command Prompt Window
  2. Navigate to the directory where your Python script (.py file) is located using the ‘cd’ command
  3. Execute your script by typing ‘python’ followed by the name of your script
How to Run a Python Script

There are multiple ways to run a script, and by the end of this article, you’ll have a solid understanding of how to run Python scripts in different environments and operating systems.

Understanding each method can improve your programming experience and help you adapt to different scenarios.

Let’s get into it!

6 Methods to Run a Python Script

In this section, we will cover 6 ways of running a Python Script.

Specifically, we will go over the following:

  1. Running a Python Script From Command Line
  2. Running a Python Script From Python Interactive Shell
  3. Running a Python Script in IDE
  4. Running a Python Script in IDLE
  5. Running a Python Script Using Import
  6. Running a Python Script Using runpy.run_module() And runpy.run_path()
6 Ways to Run Python Scripts

1) How to Run a Python Script From Command Line

The process of running a Python script from the command line is quite similar across different operating systems.

In this section, we will look at how you can:

  1. Run Python scripts from the command line on Windows
  2. Run Python scripts from the command line on Linux and MacOS

1) How to Run Python Scripts From The Command Line on Windows

You can use the following steps to run a Python program from the command line on Windows:

Step 1: Open the Command Line Interface. You can do this by searching for cmd in the start menu or by pressing Win+R, typing cmd, and then hitting Enter.

Opening Command Prompt

Step 2: Navigate to the directory containing your Python script using the cd command.

For example, if your script is in a directory on your local drive E in a folder named “PythonScripts”, you would type cd E\PythonScripts.

Navigating to file directory

Step 3: Run the script by typing python script.py (replace script.py with the name of your script), and press Enter.

Running Python script

2) How to Run Python Scripts From The Command Line on Linux And MacOS

Follow the steps listed below to run Python scripts from the command line on Linux and MacOS:

Step 1: Open the terminal.

Step 2: Navigate to the directory containing your Python script using the cd command.

For example, if your script is in a directory in your home folder named “PythonScripts”, you would type cd ~/PythonScripts.

Step 3: To run your script, type python3 script.py (replace script.py with the name of your script), and press Enter.

2) How to Run Python Script From Python Interactive Shell

The Python Interactive Shell, also known as the Python Interpreter, is an excellent tool for trying out small snippets of Python code and doing simple calculations, but it’s not the best tool for running large, complex scripts.

However, if you want to run a Python script from the Python Interactive Shell, you can do so using Python’s built-in execfile() function in Python 2, or using the exec() function with open() in Python 3.

Running Python Script From Python Interactive Shell

Running a Python Script in Python 2

Follow the steps below to run a script from the Python interactive shell in Python 2:

Step 1: Open the Python Interactive session by typing python into your terminal or command prompt and hitting Enter.

Step 2: Type execfile(‘script.py’), replacing ‘script.py’ with the path to your script.

For example:

>>> execfile('C:/Users/username/Desktop/script.py')

Running a Python Script in Python 3

In Python 3, the execfile() function has been removed. Instead, you can use exec() with open() to achieve the same effect.

Follow the steps below to run a script in Python 3:

Step 1: Open the Python Interactive Shell by typing python3 (or python if Python 3 is your default Python) into your terminal or command prompt and hitting Enter.

Step 2: Type the following, replacing ‘script.py’ with the path to your script.

>>> exec(open('C:/Users/username/Desktop/script.py').read())

The output for the above execution will be:

Running a Python Script in Python 3

3) How to Run a Python Script in IDE

You can run Python scripts in different Integrated development environments, and each has its own way of executing scripts.

For instance, if you’d like to run a Python script in VS Code, you can follow the steps given below:

Step 1: Launch Visual Studio Code, and open your Python file (File > Open File…).

If you haven’t created a Python file yet, create a new file (File > New File), and make sure to save it with a .py extension.

Step 2: Select a Python interpreter by clicking on the Python version in the bottom left of the status bar, or use the command palette (Ctrl+Shift+P) and search for “Python: Select Interpreter”.

This will show a list of available interpreters that VS Code can find automatically, including virtual environment interpreters.

Selecting an interpreter

Step 3: Once you have written your Python script and selected the Python interpreter, you can open a new terminal in VS Code to execute the script.

Running a Python Script in IDE

If you are using a Python virtual machine, you can use the same steps as discussed above after creating a virtual environment.

4) How to Run Python Script in Python’s IDLE

Python’s IDLE (Integrated Development and Learning Environment) is a simple IDE that comes with Python.

To run a Python script in IDLE, you can follow the steps given below:

Step 1: You can launch Python IDLE from your Start Menu (Windows), Applications folder (macOS), or application launcher (Linux).

Simply search for IDLE and click on the icon.

Opening IDLE

Step 2: Once IDLE is open, you can load your Python script into the IDLE text editor. Go to File > Open… in the menu bar.

Navigate to your Python script in the file dialog, select it, and click Open.

Step 3: After the script is loaded into the IDLE text editor, you can run it by going to Run > Run Module in the menu bar, or simply by pressing the F5 key.

Running the script

Step 4: The output from your script will be displayed in the Python Shell window.

If your script includes input calls like input(), the shell will also provide a prompt for user input.

Output of the script

5) How to Run a Python Script Using Import

Running a Python script using import essentially involves treating the script as a module.

When you import the script, Python will execute it from top to bottom, just as if you’d run the script directly.

Suppose you have a Python script named myscript.py with the following content:

# myscript.py

def greet():
    print("Hello from myscript!")

print("This will be printed upon import!")

You can run the script by importing it.

Open the Python shell by typing python or python3 (depending on your installation) in the terminal. Navigate to the directory containing myscript.py or make sure myscript.py is in a directory that’s part of your PYTHONPATH.

Import myscript with the following code:

>>> import myscript

The output of this execution will be:

Running a Python Script Using Import

6) How to Run a Python Script Using runpy.run_module() And runpy.run_path()

The runpy module in Python allows you to execute Python code dynamically.

It contains two main functions, run_module() and run_path(), which can be used to run Python scripts.

1) runpy.run_module()

The run_module() function allows you to execute a Python module without importing it.

It runs the module as if it was invoked from the command line using the -m option.

The following is an example of this method:

import runpy

# Run a standard library module as a script
# Equivalent of running "python -m http.server" from the command line
runpy.run_module(mod_name='http.server', run_name='__main__', alter_sys=True)

In this example, the http.server module from the Python standard library is being run, which will start a simple HTTP server.

2) runpy.run_path()

The run_path() function allows you to execute a Python script located at a specific path.

It reads and runs the Python file specified as the path.

The following is an example of run_path():

import runpy

# Run a script file as a standalone script
runpy.run_path('path_to_script.py', run_name='__main__')

In this example, replace ‘path_to_script.py’ with the actual path to your Python script.

This will execute the script just like running python path_to_script.py from the command line.

Running a Python Script Using  runpy.run_path()

Supercharge your analytics game with Code Interpreter by watching the following video:

Final Thoughts

Mastering the various ways to run a Python script is an invaluable skill for any programmer. It allows you to test and execute your code across diverse platforms and environments.

By learning these techniques, you’ll find that you have more flexibility and control in your development process, whether it’s running scripts from the command line, an IDE, or even using Python’s own tools like import and runpy.

Each method discussed offers unique benefits, be it the simplicity of running scripts in an IDE, the powerful control provided by command-line execution, or the dynamic capabilities of the import statement and runpy.

Frequently Asked Questions

In this section, you will find some frequently asked questions you may have when running Python scripts.

Male Programmer writing Python code

How do I execute a Python script in terminal?

To execute a Python script in the terminal, simply type python followed by the file name, including the “.py” extension.

For example, to run a script called “script.py”, you would type:

python script.py

What is the command to run a Python script from the command line?

The command to run a Python script from the command line is the same as executing it in the terminal.

Use python followed by the file name with the “.py” extension.

For instance:

python script.py

How can I run a .py file in Windows?

To run a .py file in Windows, open the Command Prompt and navigate to the directory containing the .py file.

Then, use the command python followed by the file name with the “.py” extension.

For example:

python script.py

What are the steps to run a Python script in a specific folder?

To run a Python script in a specific folder, follow these steps:

  1. Open the terminal or command prompt.
  2. Navigate to the folder containing the .py file using the cd command. For example:
cd path/to/your/script-folder
  1. Run the Python script using the python command followed by the file name:
python script.py

How can I execute Python code in Visual Studio Code?

To execute Python code in Visual Studio Code, follow these steps:

  1. Open the Python file in Visual Studio Code.
  2. Ensure that the Python extension is installed and correctly configured.
  3. Click the “Run” button in the top-right corner, or right-click in the editor and select “Run Python File in Terminal”.

Is it possible to run a Python script in the background?

Yes, it is possible to run a Python script in the background. This can be achieved using various methods, such as appending an ampersand (&) to the command in Unix-like systems or using the start command in Windows.

For example:

  • On Unix-like systems:
python script.py &
  • On Windows:
start python script.py
author avatar
Sam McKay, CFA
Sam is Enterprise DNA's CEO & Founder. He helps individuals and organizations develop data driven cultures and create enterprise value by delivering business intelligence training and education.

Related Posts