Python Utility Functions Overview

  • Share this:

Code introduction


The function generates a random string, gets the IP address, validates an email format, creates a directory, reads file content, calculates the square root, lists files in a directory, executes a system command, and returns these values.


Technology Stack : Built-in libraries: math, os, random, re, socket, string, subprocess

Code Type : Code function

Code Difficulty : Intermediate


                
                    
import math
import os
import random
import re
import socket
import sys

def generate_random_string(length, chars=string.ascii_letters + string.digits):
    return ''.join(random.choice(chars) for _ in range(length))

def get_ip_address():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('8.8.8.8', 80))
        ip_address = s.getsockname()[0]
        s.close()
    except socket.error:
        ip_address = '127.0.0.1'
    return ip_address

def is_valid_email(email):
    pattern = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
    return re.match(pattern, email) is not None

def create_directory(path):
    try:
        os.makedirs(path, exist_ok=True)
        return True
    except OSError:
        return False

def read_file_content(file_path):
    try:
        with open(file_path, 'r') as file:
            return file.read()
    except FileNotFoundError:
        return None

def calculate_square_root(number):
    return math.sqrt(number)

def list_files_in_directory(directory_path):
    try:
        return os.listdir(directory_path)
    except FileNotFoundError:
        return []

def execute_system_command(command):
    try:
        result = subprocess.check_output(command, shell=True, text=True)
        return result
    except subprocess.CalledProcessError as e:
        return str(e)

def xxx(arg1, arg2):
    random_string = generate_random_string(arg1)
    ip_address = get_ip_address()
    is_valid = is_valid_email(arg2)
    created = create_directory('new_directory')
    content = read_file_content('sample.txt')
    sqrt_value = calculate_square_root(arg1)
    files = list_files_in_directory('current_directory')
    command_output = execute_system_command('echo Hello World')
    return random_string, ip_address, is_valid, created, content, sqrt_value, files, command_output