How to run a Python script

26 feb 2024 5 min di lettura
How to run a Python script
Indice dei contenuti

Introduction

Python is becoming increasingly popular as a versatile and widely used programming language, known for its readability and ease of use. Whether you're a beginner or an experienced developer, Python scripting is a vital 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 any programming language. If the script is written in Python, it is called 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).

let's begin

Before getting started, make sure you have Python installed on your system. You can download the latest version from the official Python website. Once installed, open terminal or command prompt to check your 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's always a good idea to use an editor that provides syntax support, autoindentation, and autocomplete. vi, vim, and nano are powerful command-line editors. Visual Studio Code, PyCharm, and Spyder are IDEs commonly used for writing Python code.

Running a Python script from the command line

Typically, scripts are used to perform specific tasks and are run 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 contents:

print("Hello, World!")

Save the file in a directory of your choice.

  • Go to the script directory

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

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

Now it's time to run your Python script. At 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 boring to type python every time on the command line, 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 execute scripts directly without explicitly invoking the Python interpreter.

This sequence of characters ( #! ) is called a 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 in one 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 to the top 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, go 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 type the script name with the ./ prefix:

./hello.py
Hello, World!

Run scripts with script arguments

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

Let's create a more complicated function that uses the Parsing argument:

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 takes a single argument, a name:

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

python hello.py John

Which will produce this:

Hello, John!

Running Python code interactively in the terminal

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

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

Here are some examples:

2 + 3
5
x = 10
 y = 10
 x * 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 easy, many developers prefer to use integrated development environments (IDEs) for a more interactive, 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 don't already have Visual Studio Code installed, download it here and follow the installation instructions.

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

Click 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 run, 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 launch Jupyter Notebook:

jupyter notebook

This will open Jupyter Notebook in your default web browser.

Click "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, cloud-based environment. Follow these steps to run a Python script in Google Colab:

Open your web browser and go to Google Colab.

Click "File" and select "New Notebook" from the drop-down menu.

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

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

Click 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 the script. Press Shift+Enter to execute the cell and you should see the script output.

Conclusion

Mastering Python scripting is crucial for everyone, given the importance of the language. 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 get into. Each option has its use cases. Command line execution is fast and essential, while IDEs enhance the development experience with the versatility of Visual Studio Code and broad plug-in 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 your project specifics and workflow preferences, and experimenting with various approaches aligns with your coding style and project needs. Efficiently executing Python scripts is a foundational skill that opens possibilities in software development, data science, and more.

Support us with a

Successivamente, completa il checkout per l'accesso completo a Noviello.it.
Bentornato! Accesso eseguito correttamente.
Ti sei abbonato con successo a Noviello.it.
Successo! Il tuo account è completamente attivato, ora hai accesso a tutti i contenuti.
Operazione riuscita. Le tue informazioni di fatturazione sono state aggiornate.
La tua fatturazione non è stata aggiornata.