Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to run a Python script in linux

Introduction

Welcome to this tutorial on running Python scripts in Linux! If you're learning programming and are new to Python or Linux, this tutorial is perfect for you. We'll be covering everything you need to know to get started with running Python scripts on a Linux system.

Python is a versatile programming language that is widely used in various fields such as web development, data analysis, artificial intelligence, and more. Linux, on the other hand, is a popular open-source operating system that is known for its stability, security, and flexibility.

In this tutorial, we'll be walking you through the following steps:

  1. Installing Python on Linux
  2. Creating a Python script
  3. Running a Python script in Linux
  4. Using command-line arguments in Python scripts
  5. Scheduling Python scripts using cron jobs

Let's dive right in!

Installing Python on Linux

Before we can run any Python scripts, we need to make sure that Python is installed on our Linux system. Most Linux distributions come with Python pre-installed, but it's always a good idea to check the version and update it if needed.

To check if Python is installed and to see its version, open a terminal window and type the following command:

python --version

If Python is installed, you should see the version number in the output. If it's not installed, or if you want to install a different version, you can follow the instructions below for your specific Linux distribution.

Installing Python on Ubuntu/Debian

To install Python on Ubuntu or Debian, use the following commands:

sudo apt update
sudo apt install python3

Installing Python on CentOS/RHEL

For CentOS or RHEL, use the following commands:

sudo yum update
sudo yum install python3

Installing Python on Fedora

For Fedora, use the following commands:

sudo dnf update
sudo dnf install python3

Once Python is installed, you can verify the installation by checking the version again:

python3 --version

Now that we have Python installed, let's create a Python script!

Creating a Python script

A Python script is a simple text file that contains Python code. To create a Python script, all you need is a text editor. You can use any text editor that you're comfortable with, such as nano, vim, or gedit.

Let's create a simple Python script that prints "Hello, World!" to the console. Open your favorite text editor and type the following code:

print("Hello, World!")

Save the file with a .py extension, for example, hello_world.py. The .py extension is not mandatory, but it's a good practice to use it to indicate that the file contains Python code.

Running a Python script in Linux

Now that we have our Python script, let's see how to run it in Linux. There are multiple ways to run a Python script, but we'll be focusing on two methods: using the python command and running the script as an executable file.

Method 1: Using the python command

The most straightforward way to run a Python script is to use the python command followed by the script's file name. Open a terminal window, navigate to the directory where your Python script is saved, and type the following command:

python3 hello_world.py

You should see the output "Hello, World!" printed to the console.

Method 2: Running the script as an executable file

Another way to run a Python script is by making the script an executable file. This method is useful when you want to run a script without typing the python command every time. To make the script executable, follow these steps:

  1. Add a "shebang" line at the beginning of the script. A shebang is a special line that tells the operating system which interpreter should be used to run the script. In our case, we want to use the Python interpreter. Add the following line at the top of your hello_world.py script:

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

The #!/usr/bin/env python3 line indicates that the script should be run using Python 3.

  1. Change the file permissions to make the script executable. In the terminal, navigate to the directory where your script is saved, and type the following command:

bash chmod +x hello_world.py

This command adds the "execute" permission to the script, allowing it to be run as an executable file.

  1. Now you can run the script by typing the following command in the terminal:

bash ./hello_world.py

You should see the "Hello, World!" output printed to the console.

Using command-line arguments in Python scripts

In many cases, you might want your Python script to accept input from the user when it's run. One way to do this is by using command-line arguments. Command-line arguments are values that are passed to the script when it's run in the terminal.

To use command-line arguments in your Python script, you'll need to import the sys module, which provides access to the argv list. The argv list contains the command-line arguments that were passed to the script.

Let's modify our hello_world.py script to accept a name as a command-line argument and print a personalized greeting:

#!/usr/bin/env python3
import sys

if len(sys.argv) > 1:
    name = sys.argv[1]
    print(f"Hello, {name}!")
else:
    print("Hello, World!")

Now, when you run the script with a command-line argument, you should see a personalized greeting:

./hello_world.py Alice

Output:

Hello, Alice!

Scheduling Python scripts using cron jobs

Sometimes, you might want to run a Python script automatically at specific intervals. For example, you might want to run a script that backs up your data every day at a specific time. In Linux, you can schedule tasks like this using "cron jobs."

A cron job is a scheduled task that runs automatically at specified intervals. To create a cron job, you'll need to edit the "crontab" file, which is a configuration file that contains a list of all your scheduled tasks.

To edit the crontab file, open a terminal window and type the following command:

crontab -e

This command opens the crontab file in your default text editor. To schedule a Python script, add a new line to the file with the following format:

* * * * * /path/to/python3 /path/to/your_script.py

The five asterisks represent the following time fields, in order:

  1. Minute (0-59)
  2. Hour (0-23)
  3. Day of the month (1-31)
  4. Month (1-12)
  5. Day of the week (0-7, where both 0 and 7 represent Sunday)

To schedule a script to run every day at 3:30 PM, for example, you would add the following line to your crontab file:

30 15 * * * /path/to/python3 /path/to/your_script.py

Save the crontab file, and your Python script will now run automatically at the specified time.

Conclusion

Congratulations! You now know how to run Python scripts in Linux, use command-line arguments, and schedule your scripts using cron jobs. With these skills, you can automate tasks, create useful tools, and build powerful applications using Python and Linux.

Remember to practice and experiment with different Python scripts and Linux commands to become more familiar with the process and improve your skills. Happy coding!