How to Run a Python Script

Published on

6 min read

By 

Raghav Maddukuri
Run a Python Script

Python is growing in popularity as a versatile and widely used programming language known for its readability and ease of use. Whether you are a beginner or an experienced developer, Python scripting is a fundamental skill.

In computing, a script is a list of commands and instructions interpreted by a specific program. The term ‘script’ is very generic and applies to every programming language. If the script is written in Python, it is called a Python Script.

This guide will walk you through the step-by-step process of running a Python script, covering both command-line execution and using integrated development environments (IDEs).

Getting Started

Before we start, ensure that you have Python installed on your system. You can download the latest version from the official Python website . Once it’s installed, open your terminal or command prompt to check the Python version by typing:

python --version

If you see a version number, you’re good to go! Now, let’s move on to running a simple Python script.

When writing scripts, it is always a good idea to use an editor that provides syntax support, auto-indentation, and auto-completion. vi, vim, and nano are powerful command line editors. Visual Studio Code, PyCharm, and Spyder are commonly used IDEs for writing Python code.

Running a Python Script from the Command Line

Generally, the scripts are used to accomplish specific tasks and are executed from the command line.

  • Create a Python Script

    Open your favorite text editor or integrated development environment (IDE) and write a simple Python script. For example, create a file named hello.py with the following content:

    print("Hello, World!")
    

    Save the file in a directory of your choice.

  • Navigate to the Script’s Directory

    Open your terminal or command prompt and navigate to the directory where you saved your Python script using the cd command. For instance:

    cd /path/to/your/script/directory
  • Run the Script

    Now, it’s time to execute your Python script. In the command line, type:

    python hello.py

    Press Enter, and you should see the output:

    Hello, World!
    

Congratulations! You have successfully run your first Python script.

Run Python Scripts Using Shebang

If you find it tedious to type python on the command line every time, you can use shebang in the script file. This approach is particularly useful on Unix-like systems (such as Linux and macOS), allowing you to run scripts directly without explicitly invoking the Python interpreter.

This sequence of characters (#!) is called shebang and is used to tell the operating system which interpreter to use to parse the rest of the file. Shebang makes the script more portable.

Shebang works with either of the following ways.

#!/usr/bin/python
 or 
#!/usr/bin/env python

Here’s how to use a shebang in your Python scripts.

First, open the Python script in a text editor and add the following line at the very beginning of the file:

#!/usr/bin/env python
print("Hello, World!")

The next step after adding the shebang line, is to make the script executable. In the terminal, navigate to the directory containing your Python script and run the following command:

chmod +x hello.py

Now that the script is executable, you can run it directly from the command line without explicitly calling the Python interpreter. All you have to do is to type the script name prefixed with ./:

./hello.py
Hello, World!

Run Scripts with Script Arguments

Python scripts can accept command-line arguments, allowing greater flexibility and customization. We can use these arguments and pass them to the script when they are executed, enabling us to provide input or specify options dynamically.

Let’s make a more complicated function that utilizes argument Parsing:

import argparse

def main():
    parser = argparse.ArgumentParser(description='A script that greets a user.')
    parser.add_argument('name', help='The name of the person to greet')
    args = parser.parse_args()
    greet(args.name)

def greet(name):
    print(f'Hello, {name}!')

if __name__ == '__main__':
    main()

This code above is made to expect a single argument, a name:

Now, to utilize this code, we need to run the following command:

python hello.py John

Which will output this:

Hello, John!

Running Python Code Interactively in the Terminal

On the command line, type python or python3 and then press Enter. This command will start the Python interpreter and display the Python version information along with a prompt (>>>) indicating that Python is ready to accept commands.

Once you see the >>> prompt, you can start executing Python code. For example, you can perform simple arithmetic operations, define variables, or write small functions. Make sure to press Enter after each line to execute the code.

Here are some examples:

2 + 3
5
x = 10y = 10x * y
200
def greet(name):  return f "Hello, {name}!"greet("Alice")
'Hello, Alice!'
days = "23"days_int = int(days)type(days_int)
<type 'int'>

Running a Python Script in an IDE

While running scripts from the command line is straightforward, many developers prefer using integrated development environments (IDEs) for a more interactive and feature-rich experience. Let’s explore how to run a Python script in two popular IDEs: Visual Studio Code and Jupyter Notebook.

Running a Python Script in Visual Studio Code

If you haven’t already installed Visual Studio Code, download it here and follow the installation instructions.

Launch Visual Studio Code and open the folder containing your Python script.

Click on the “View” menu and select “Terminal” to open a new terminal within Visual Studio Code.

In the terminal, type the name of the script you want to execute, for example:

python hello.py

Press Enter, and you should see the output in the terminal.

Running a Python Script in Jupyter Notebook

Install Jupyter Notebook using the following command:

pip install notebook

Open your terminal and navigate to the directory containing your Python script. Type the following command to start Jupyter Notebook:

jupyter notebook

This will open Jupyter Notebook in your default web browser.

Click on “New” and select “Python 3” to create a new Python notebook.

In a new notebook cell, type the following code:

%run hello.py

Press Shift+Enter to execute the cell, and you should see the script output below the cell.

Running a Python Script in Google Colab

Google Colab provides a convenient platform for running Python scripts in a collaborative and cloud-based environment. Follow these steps to run a Python script in Google Colab:

Open your web browser and go to Google Colab .

Click on “File” and select “New Notebook” from the dropdown menu.

If your script relies on files stored in Google Drive, you can mount your drive by running the following code in a Colab cell:

from google.colab import drive
drive.mount('/content/drive')

Click on the folder icon in the left sidebar, then click the “Upload” button. Select your python script and upload it.

In a Colab cell, type:

!python /content/drive/MyDrive/path/to/your/script/hello.py

Replace the path with the actual path to your script. Press Shift+Enter to execute the cell, and you should see the script output.

Conclusion

Mastering Python scripts is pivotal for everyone, given the language’s prominence. The options, including command-line execution, IDEs like Visual Studio Code, and cloud-based platforms like Jupyter Notebook and Google Colab, make the language easy to approach. Each option has its use cases. Command-line execution is quick and fundamental, while IDEs enhance the development experience with Visual Studio Code’s versatility and extensive plugin support. Jupyter Notebook offers an interactive and visually appealing environment suitable for data exploration, while Google Colab, being cloud-based, facilitates collaborative work and provides access to powerful hardware accelerators. The choice depends on project specifics and workflow preferences, and experimenting with various approaches aligns with the coding style and project needs. Efficiently running Python scripts is a foundational skill that unlocks possibilities in software development, data science, and beyond.

About the authors

Raghav Maddukuri