Where Python Linux: Using Python on Linux Systems

10 Min Read

Where Python meets Linux: A Guided Tour for code-savvy friend 😋 Coders! 🐍🐧

Hey everyone! 💻 So, picture this: you’re a coding ninja slicing through the digital jungle, and your weapon of choice is Python. But wait, you’ve decided to level up and venture into the Linux terrain! 😎 Don’t worry, I’ve got your back! Let’s navigate the curious world of using Python on Linux systems together! 🚀

I. Installing Python on Linux

A. Checking for Python Installation

Now, before we embark on this adventure, let’s make sure Python is already camping out in your Linux system. Let’s roll!

  1. Using Terminal Command 🖥️
    Fire up your terminal and type in python --version or python3 --version. If you spot some version numbers popping up, you’re good to go!

  2. Using Package Manager 📦
    For the Debian-based systems, such as Ubuntu, you can use the command dpkg -l | grep python. For Red Hat-based folks, the rpm -qa | grep python command will do the trick.

B. Installing Python

So, you didn’t find Python snuggled up in your Linux nook? Don’t fret! We’ll fetch it in no time!

  1. Using Package Manager 🚚
    For Debian-based systems, execute sudo apt-get install python3. Red Hat-based fans can go for sudo yum install python3.

  2. Building from Source 🏗️
    Feeling adventurous? Then roll up your sleeves, grab the source code from Python’s official website, and build it like a boss! It’s a bit of a handiwork, but totally doable!

II. Python Development on Linux

A. Text Editors and IDEs

Alright, girl, when it comes to crafting those beautiful lines of Python magic, you’ve got choices aplenty!

  1. Using Terminal Editors (e.g. Vim, Nano) 📝
    Wanna keep it old school? Go all-in with Vim if you’re daring, or Nano if you want a smoother ride.

  2. Using Integrated Development Environments (e.g. PyCharm, VSCode) 💻
    For the modern vibe, cozy up with PyCharm or soothe your coding soul with the sweetness of VSCode.

B. Setting Up Virtual Environments

Now, this is where the magic happens! Virtual environments are like little Python wonderlands where you can play without messing up the main castle.

  1. Using venv 🔮
    Whip up a virtual environment using python3 -m venv myenv, and you’re all set to rock and roll!

  2. Using Conda 🐍
    Fancy a taste of Anaconda? Then conda create --name myenv will create a virtual oasis for your Python projects.

III. Running Python Scripts on Linux

A. Command Line Execution

Ready to fire off your Python spells from the command line?

  1. Running a script
    Simply type python script_name.py or python3 script_name.py, and watch the magic unfold!

  2. Passing command line arguments 🎯
    Need to make your scripts more dynamic? Pass those command line arguments like a pro with sys.argv or the argparse module!

B. Scheduled Tasks and Automation

The time has come to automate your Python sorcery!

  1. Using Cron Jobs
    Set up scheduled Python tasks using the venerable cron and watch your scripts dance to a predefined beat!

  2. Python Scripts as System Services 🛠️
    Elevate your Python scripts to ninja status by transforming them into system services. Let them run in the shadows, always vigilant and ready to serve!

IV. Package Management with Python on Linux

A. Using Pip

Time to unleash the power of Pip, the Python package installer!

  1. Installing Packages 📦
    Need a new Python package? Just command pip install package_name and watch Pip do its thing!

  2. Managing Dependencies 🛠️
    Keep your dependencies spick and span with pip freeze and pip install -r requirements.txt. Clean house, no clutter for you!

B. Using Package Managers

Sometimes, you need more than just Python packages!

  1. Installing System-wide Libraries 📚
    Dial up your system’s package manager—be it APT, YUM, or DNF—and bring in those system-level libraries like a boss!

  2. Managing External Dependencies 🌐
    Handle external dependencies using tools like ldconfig or pkg-config and keep your Python projects from getting entangled!

V. Executing System Commands with Python

A. Subprocess Module

Ready to wield the power of the system from within Python? The subprocess module is your Excalibur!

  1. Running External Commands ⚔️
    Run system commands using Python as your loyal vassal. subprocess.run('command', shell=True) is your trusted servant in this endeavor.

  2. Capturing Output and Errors 📡
    Use stdout, stderr, and the versatile subprocess.PIPE to harness the output and errors of your system commands as you wish!

B. File and Directory Operations

It’s time to juggle some files and folders with Python!

  1. Managing Files and Directories 📂
    Use os and shutil modules to juggle files and directories like a digital acrobat. Copy, move, rename—it’s all in your hands!

  2. Working with Permissions and Ownership 🔐
    Adjust file permissions and ownership with os.chmod, os.chown, and other similar enchantments. Your files will obey your every command!

Finally, remember, the majestic Python and the steadfast Linux make for an invincible duo! Make the most out of this powerful pairing and become the coder-extraordinaire you were destined to be! 🌟

overall, diving into the uncharted waters of using Python on Linux has been an absolute blast! I’ve learned so much, and I hope you did too. Remember, when in doubt, just keep coding! Until next time, happy coding and may the bugs be ever in your favor! 😄👩‍💻

Program Code – Where Python Linux: Using Python on Linux Systems


#!/usr/bin/env python3
# A Python script to demonstrate usage on a Linux system

import os
import subprocess
import sys

# Function to check the current operating system
def check_os():
    if os.name != 'posix':
        print('This script is designed to run on Linux or other POSIX systems only.')
        sys.exit(1)

# Function to get system info using Linux commands
def get_system_info():
    try:
        # Prints the Linux distribution
        print('Linux Distribution:', subprocess.check_output('lsb_release -a', shell=True).decode())

        # Prints the current user
        print('Current User:', subprocess.check_output('whoami', shell=True).strip().decode())

        # Prints the number of CPU cores
        print('CPU Cores:', subprocess.check_output('nproc', shell=True).strip().decode())

        # Prints the current memory usage
        memory_usage = subprocess.check_output('free -m', shell=True).decode()
        print('Memory Usage (in MB):')
        print(memory_usage)

        # Prints the disk usage
        disk_usage = subprocess.check_output('df -h', shell=True).decode()
        print('Disk Usage:')
        print(disk_usage)

    except Exception as e:
        print(f'An error occurred: {e}')

# Check if the script is run on Linux
check_os()

# Print system info
get_system_info()

Code Output:

  • Linux Distribution: Information related to the Linux distribution will be printed here.
  • Current User: username of the current logged in user.
  • CPU Cores: the number of CPU cores on the system.
  • Memory Usage (in MB): current memory usage details in MB.
  • Disk Usage: current disk usage displayed in a human-readable format.

Code Explanation:

The script starts by checking if it is being run on a Linux system through the check_os function. It checks if the os.name is ‘posix,’ which indicates a POSIX-compatible system like Linux. If it’s not, the script exits promptly with a message.

Assuming the check passes, get_system_info is called next. This function utilizes subprocess calls to gather system information. It captures and decodes the output of Linux commands:

  • lsb_release -a gets details of the Linux distribution.
  • whoami retrieves the currently logged-in user’s name.
  • nproc provides the number of processing units available.
  • free -m offers the memory usage in megabytes.
  • df -h displays disk usage in a human-readable format.

Each command’s output is decoded from bytes to a string for printing. Should any command fail, the script catches the exception, printing an error message.

The script aims to give a quick overview of some basic system stats by tapping into the command-line tools native to Linux, demonstrating Python’s ability to seamlessly work and interact with the underlying system. This reflects a common use case for Python in Linux environments – system administration and gathering system metrics.

Share This Article
Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *

English
Exit mobile version