DevOps
Python Scripting
Running Scripts

Running Python Scripts on Ubuntu

This guide provides a step-by-step workflow for setting up and running Python scripts on an Ubuntu-based system.

Step 1: Check Python Installation

Ubuntu usually comes with Python pre-installed. You should verify the version to ensure you are using Python 3.

# Check version
python3 --version

If it's not installed, you can install Python and its package manager (pip) using:

sudo apt update
sudo apt install python3 python3-pip

Step 2: Create a Script

Use a command-line text editor like nano to create your first script.

# Create a directory for your work
mkdir ~/python-scripts && cd ~/python-scripts
 
# Create a new file
nano myscript.py

Inside the editor, write your logic:

print("Hello from the Python script!")
print("DevOps automation is starting...")

Press Ctrl + O then Enter to save, and Ctrl + X to exit.


Step 3: Standard Execution

The simplest way to run your script is by passing the filename to the python3 interpreter.

python3 myscript.py

Step 4: Making the Script Executable

In DevOps, we often want to run scripts directly without explicitly calling the interpreter. We do this using a Shebang line and Permissions.

1. Add the Shebang

Edit your file and add this line as the very first line:

#!/usr/bin/env python3
print("Running as an executable!")

2. Grant Execute Permission

Use the chmod command to make the file executable.

chmod +x myscript.py

3. Run Directly

Now you can run the script using its path:

./myscript.py

Conclusion

You now have a complete workflow for running Python automation on Linux.

  1. Check Environment: Ensure Python 3 is ready.
  2. Code: Write logic in .py files.
  3. Optimize: Use Shebangs and Chmod to turn your scripts into standalone tools.

[!TIP] Why #!/usr/bin/env python3? Using env helps find the Python 3 interpreter in your system path automatically, making your script more portable across different Linux distributions compared to a static path like #!/usr/bin/python3.