10 Advanced Python Commands for Interacting with the Operating System

Time: Column:Python views:308

Today, we will discuss advanced ways to interact with the operating system using Python. The operating system acts as a bridge between computer hardware and applications, and Python provides libraries that allow us to easily interact with the OS. Whether on Windows or Linux, Python helps us perform a variety of tasks.

10 Advanced Python Commands for Interacting with the Operating System

1. Viewing the Current Working Directory

First, let’s see how to check the current working directory, which is useful when dealing with file paths.

import os

# Get the current working directory
current_directory = os.getcwd()
print("Current working directory:", current_directory)

Output:

Current working directory: /path/to/your/current/directory

2. Listing All Files in a Directory

Next, let’s learn how to list all files in a directory. This is essential for automation scripts.

import os

# List all files in the current directory
files = os.listdir('.')
for file in files:
    print(file)

Output:

file1.txt
file2.jpg
folder1

3. Creating a New Directory

Sometimes, we need to create a new directory to organize files. Here's a simple example.

import os

# Create a new directory
new_dir = 'new_folder'
os.mkdir(new_dir)
print(f"Directory {new_dir} has been created")

Output:

Directory new_folder has been created

4. Deleting a Directory

When a directory is no longer needed, we can delete it.

import os

# Remove a directory
dir_to_remove = 'new_folder'
os.rmdir(dir_to_remove)
print(f"Directory {dir_to_remove} has been removed")

Output:

Directory new_folder has been removed

5. Running External Commands

Python allows us to run external commands directly, which is very convenient for performing specific tasks.

import subprocess

# Run an external command
command = "ls -l"
result = subprocess.run(command, shell=True, text=True, capture_output=True)
print(result.stdout)

Output:

total 0
drwxr-xr-x 2 user user 4096 Mar 1 14:00 folder1
-rw-r--r-- 1 user user    0 Mar 1 14:00 file1.txt

6. Retrieving System Information

Retrieving system information helps us better understand the runtime environment.

import platform

# Get system information
info = platform.uname()
print(f"System: {info.system}")
print(f"Node Name: {info.node}")
print(f"Version: {info.release}")

Output:

System: Linux
Node Name: mycomputer
Version: 5.4.0-77-generic

These are some of the advanced ways Python can interact with the operating system, providing flexibility and control over the environment.

Monitoring File Changes

Sometimes we need to monitor changes in files or directories, such as for automatic backups.

from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

class MyHandler(FileSystemEventHandler):
    def on_modified(self, event):
        print(f"{event.src_path} has been modified")

if __name__ == "__main__":
    path = "."
    event_handler = MyHandler()
    observer = Observer()
    observer.schedule(event_handler, path, recursive=True)
    observer.start()
    try:
        while True:
            pass
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

This code will listen for changes in all files within the current directory and print modification information.

Copying Files

Copying files is one of the common tasks in daily work. Python’s shutil module provides the functionality to copy files.

import shutil

# Source and destination files
source_file = 'file1.txt'
destination_file = 'copy_of_file1.txt'

# Copy the file
shutil.copy(source_file, destination_file)
print(f"File {source_file} has been copied to {destination_file}")

Output:

File file1.txt has been copied to copy_of_file1.txt

Moving Files

In addition to copying files, moving files is also a common task. This can also be done using the shutil module.

import shutil

# Source and destination files
source_file = 'copy_of_file1.txt'
destination_file = 'folder1/moved_file1.txt'

# Move the file
shutil.move(source_file, destination_file)
print(f"File {source_file} has been moved to {destination_file}")

Output:

File copy_of_file1.txt has been moved to folder1/moved_file1.txt

Managing File Permissions

In some cases, we need to manage file permissions, such as changing the owner or setting file permissions.

import os

# File path
file_path = 'folder1/moved_file1.txt'

# Change file permissions
os.chmod(file_path, 0o777)  # Set file permissions to readable, writable, and executable
print(f"Permissions for {file_path} have been changed to 0777")

# Change file ownership
# On Linux, you can change the file owner using os.chown()
# However, this usually requires root privileges, and is not recommended in Python scripts
# If necessary, you can use the following code:
# os.chown(file_path, uid, gid)

Output:

Permissions for folder1/moved_file1.txt have been changed to 0777

Real-World Example: Automatic Backup Tool

Suppose you have an important folder that needs to be backed up regularly. We can write a Python script to automatically perform this task. Here's a simple example:

import os
import shutil
import datetime

def backup_files(source_folder, backup_folder):
    # Get the current date and time
    now = datetime.datetime.now()
    timestamp = now.strftime("%Y%m%d_%H%M%S")
    
    # Create a backup directory
    backup_subfolder = os.path.join(backup_folder, timestamp)
    os.makedirs(backup_subfolder, exist_ok=True)
    
    # Copy files
    for root, dirs, files in os.walk(source_folder):
        for file in files:
            source_file = os.path.join(root, file)
            relative_path = os.path.relpath(source_file, source_folder)
            destination_file = os.path.join(backup_subfolder, relative_path)
            os.makedirs(os.path.dirname(destination_file), exist_ok=True)
            shutil.copy2(source_file, destination_file)
    
    print(f"Backup completed: {source_folder} -> {backup_subfolder}")

if __name__ == "__main__":
    source_folder = '/path/to/source/folder'
    backup_folder = '/path/to/backup/folder'
    backup_files(source_folder, backup_folder)

Analysis:

  1. Getting Current Date and Time: The datetime module is used to get the current timestamp.

  2. Creating Backup Directory: A new subdirectory is created based on the timestamp.

  3. Copying Files: The script traverses all files in the source folder and copies them to the backup directory.

This script can be scheduled to run automatically at certain times, such as every midnight, to ensure data safety.

These are 10 advanced commands for interacting with the operating system using Python. Hopefully, these examples help you better understand and utilize Python’s powerful capabilities. If you have any questions or suggestions, feel free to discuss!